ในบทความนี้เราจะมาดูโจทย์น่าสนใจ: ตรวจสอบว่า Number เป็น Jumbled หรือไม่ Number ถือว่า Jumbled ถ้าทุก Digit ต่างจาก Digit ข้างเคียงสูงสุด 1 ตัวอย่าง 1223 เป็น Jumbled แต่ 1256 ไม่ใช่
วิธีแก้: ตรวจสอบว่ามี Digit ไหนที่ต่างจาก Neighbor มากกว่า 1 หรือไม่ ถ้ามี คืนค่า false มิฉะนั้น true
ตัวอย่างโค้ด C++
#include <iostream>
#include <cmath>
using namespace std;
bool isJumbled(int number) {
if (number / 10 == 0) // single digit is always jumbled
return true;
while (number != 0) {
if (number / 10 == 0) // all digits checked
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