在C++中檢查一個數字是否是混亂的
這裡,我們將瞭解一個有趣的問題,即如何檢查一個數字是否是混亂的。一個數字被稱為混亂數字,如果對於它的每一位數字,其相鄰數字的差值都最大為 1。例如,數字 1223 是混亂的,而 1256 不是混亂的。
為了解決這個問題,我們必須檢查一個數字是否有相鄰的數字,其差值大於 1。如果找到了這樣的數字,則返回 false,否則返回 true。
示例
#include <iostream>
#include <cmath>
using namespace std;
bool isJumbled(int number) {
if (number / 10 == 0) //for single digit number is is always jumbled
return true;
while (number != 0) {
if (number / 10 == 0) //when all digits have checked, return true
return true;
int curr_digit = number % 10;
int prev_digit = (number / 10) % 10;
if (abs(prev_digit - curr_digit) > 1)
return false;
number = number / 10;
}
return true;
}
int main() {
int n = 1223;
if(isJumbled(n)){
cout << n << " is Jumbled";
} else {
cout << n << " is not Jumbled";
}
}輸出
1223 is Jumbled
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP