How to check bouncy numbers in Java
In this shot, we discuss how to check bouncy numbers in Java.
Bouncy numbers
A bouncy number has both an increasing and decreasing sequence in in a single number, as opposed to a number that only has one or the other.
Example: , etc.
For , we can see that this number has an increasing sequence from to and a decreasing sequence from to . From to , it again has an increasing sequence. So, is a bouncy number, as it has both increasing and decreasing sequences.
Code
Let’s look at the code snippet below.
import java.util.Scanner;class Bouncy {public static void main(String[] args) {Scanner sc= new Scanner((System.in));System.out.println("Enter the number:-");int num= sc.nextInt();if(isBouncy(num)==true){System.out.println(num+" is a bouncy number");}else{System.out.println(num+" is not a bouncy number");}}static boolean isBouncy(int num){boolean isIncreasing= true,isDecreasing=true;int temp= num;// check if number is ascendingint prev= temp%10;while(temp!=0){int rem = temp%10;if(rem > prev){isIncreasing=false;break;}prev= rem;temp/=10;}temp=num;prev= temp%10;while(temp!=0){int rem = temp%10;if(rem < prev){isDecreasing=false;break;}prev= rem;temp/=10;}if(!isIncreasing && !isDecreasing){return true;}else{return false;}}}
Enter the input below
Explanation
-
In line 1, we import the
java.util.Scannerclass to read input from the user. -
In line 7, we create a
Scannerobject to take the input number from the user and store that input in an integernum. -
In line 8, we call the
isBouncy()function, which, if it returnstrue, prints that the input number"is a bouncy number". -
In lines 14 to 48, we define the
isBouncy()function. In this function, we initialize two boolean flags,isIncreasingandisDecreasing, astrue. -
In lines 18 to 29, we check if all the digits of the given number are in ascending order or not. We run a loop and check if any digit is greater than the next digit, then set the
isIncreasingflag asfalse. -
In lines 30 to 42, we repeat the previous step, but this time we check for descending order and set the
isDecreasingflag asfalse. -
In line 43, we check both the flags, and the value is returned per the condition.
In this way, we can check bouncy numbers in Java.