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: 15349,125431,98456715349 ,125431, 984567, etc.

For 1534915349, we can see that this number has an increasing sequence from 11 to 55 and a decreasing sequence from 55 to 33. From 33 to 99, it again has an increasing sequence. So, 1534915349 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 ascending
int 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.Scanner class to read input from the user.

  • In line 7, we create a Scanner object to take the input number from the user and store that input in an integer num.

  • In line 8, we call the isBouncy() function, which, if it returns true, 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, isIncreasing and isDecreasing, as true.

  • 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 isIncreasing flag as false.

  • In lines 30 to 42, we repeat the previous step, but this time we check for descending order and set the isDecreasing flag as false.

  • 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.

Free Resources