Read Also: Find first and last digit of a number in Java
Jumbled Number in Java
What is a Jumbled Number
A Jumbled number is a number whose neighbor digits i.e. (left or right) differs by max 1, then the number is a Jumbled number, otherwise not.Examples :
123232345 is a Jumbled number
// All neighbor digits differ at most by 1
2346912 is not a Jumbled number
// 4 and 6 differ by 2,
// 6 and 9 differ by 3,
// 9 and 1 differ by 8
234 is a Jumbled number
Note: All single digit numbers are by default jumbled numbers i.e. 1, 2, 3, 4, 5, 6, 7, 8, 9 are Jumbled numbers.
Java Program for Jumbled Number
Below is the Java program to check whether a given number is a jumbled Number or not using a while loop.
import java.util.Scanner;
public class JumbledNumber {
public static void main(String args[]) {
System.out.println("Enter any integer number");
Scanner scan = new Scanner(System.in);
int inputNumber = scan.nextInt();
boolean result = isJumbledNumber(inputNumber);
if (result == true)
{
System.out.println(inputNumber + " is a Jumbled Number");
}
else
{
System.out.println(inputNumber + " is NOT a Jumbled Number");
}
}
public static boolean isJumbledNumber(int inputNumber)
{
int num = inputNumber;
// All single digit numbers are Jumbled number
if (num / 10 == 0)
return true;
// Checking every digit of a number through while loop
while (num != 0)
{
// When all digits are checked
if (num / 10 == 0)
return true;
// Fetching digit at index i-1
int digit1= (num / 10) % 10;
// Fetching digit at index i
int digit2 = num % 10;
// Calculate difference between digits
int diff = Math.abs(digit2 - digit1);
if (diff > 1)
return false;
num = num / 10;
}
// When all digits are checked
return true;
}
}
Output:
433448 is NOT a Jumbled Number
2334432 is a Jumbled Number
That's all for today. Please mention in the comments if you have any questions related to how to check whether a given number is a jumbled number or not.