Write a program to check if a given integer is jumbled or not. A number is said to be Jumbled if for every digit, its neighbours digit differs by max 1.
Examples:
Input : 6765 Output : True All neighbour digits differ by atmost 1. Input : 1223 Output : True Input : 1235 Output : False
To find if a number is jumbled, we just need to check if a digit has a neighbour
with difference greater than 1. If such digit is found, the number is non-jumbled.
Below is the C++ implementation :
C++
// CPP code to check if a number is jumbled or not
#include <bits/stdc++.h>
using namespace std;
// Function to check if a number is jumbled or not
bool checkJumbled(int num)
{
// Single digit number
if (num / 10 == 0)
return true;
// Checking every digit through a loop
while (num != 0) {
// All digits were checked
if (num / 10 == 0)
return true;
// Digit at index i
int digit1 = num % 10;
// Digit at index i-1
int digit2 = (num / 10) % 10;
// If difference is greater than 1
if (abs(digit2 - digit1) > 1)
return false;
num = num / 10;
}
// Number checked
return true;
}
// Driver code
int main()
{
//-1234 to be checked
int num = -1234;
if (checkJumbled(num))
cout << "True \n";
else
cout << "False \n";
// 287 to be checked
num = -1247;
if (checkJumbled(num))
cout << "True \n";
else
cout << "False \n";
return 0;
}
Python
# Python code to check if a number is jumbled or not
# Function to check if a number is jumbled or not
def checkJumbled(num):
# Single digit number
if (num / 10 == 0):
return True
# Checking every digit through a loop
while (num != 0):
# All digits were checked
if (num / 10 == 0):
return True
# Digit at index i
digit1 = num % 10
# Digit at index i-1
digit2 = (num / 10) % 10
# If difference is greater than 1
if (abs(digit2 - digit1) > 1):
return False
num = num / 10
# Number checked
return True
# Driver code
# -1234 to be checked
num = -1234
if (checkJumbled(abs(num))):
print "True "
else:
print "False"
# -1247 to be checked
num = -1247
if (checkJumbled(abs(num))):
print "True "
else:
print "False"
# This code is contributed by Sachin Bisht
Output:
True False
Related Article :
Stepping Numbers
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

