ที่นี่เราจะเห็นปัญหาหนึ่งที่น่าสนใจในการตรวจสอบว่าตัวเลขคลาดเคลื่อนหรือไม่ มีการกล่าวกันว่าตัวเลขจะคลาดเคลื่อนหากทุกๆ หลัก เป็นตัวเลขเพื่อนบ้านแตกต่างกันสูงสุด 1 ตัวอย่างเช่น ตัวเลข 1223 จะคลาดเคลื่อน แต่ 1256 จะไม่คลาดเคลื่อน
ในการแก้ปัญหานี้ เราต้องตรวจสอบว่าตัวเลขหนึ่งมีค่าใกล้เคียงกันซึ่งมีค่ามากกว่า 1 หรือไม่ หากพบตัวเลขดังกล่าว ให้คืนค่าเท็จ มิฉะนั้น จะเป็นจริง
ตัวอย่าง
#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