Programming Examples
Java program for Bouncy Number
Write a Program in Java to input a number and check whether it is a Bouncy Number or not.
Increasing Number : Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 22344.
Decreasing Number : Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 774410.
Bouncy Number : We shall call a positive integer that is neither increasing nor decreasing a “bouncy†number; for example, 155349. Clearly there cannot be any bouncy numbers below 100.
Sample:
Enter a number : 22344
The number 22344 is Increasing and Not Bouncy
Enter a number : 774410
The number 774410 is Decreasing and Not Bouncy
Enter a number : 155349
The number 155349 is bouncy
Solution
import java.util.*;
class BouncyNumber
{
boolean isIncreasing(int n)
{
String s = Integer.toString(n);
char ch;
int f = 0;
for(int i=0; i<s.length()-1; i++)
{
ch = s.charAt(i);
if(ch>s.charAt(i+1))
{
f = 1;
break;
}
}
if(f==1)
return false;
else
return true;
}
boolean isDecreasing(int n)
{
String s = Integer.toString(n);
char ch;
int f = 0;
for(int i=0; i<s.length()-1; i++)
{
ch = s.charAt(i);
if(ch<s.charAt(i+1))
{
f = 1;
break;
}
}
if(f==1)
return false;
else
return true;
}
void isBouncy(int n)
{
if(isIncreasing(n)==true)
System.out.println("The number " + n + " is Increasing and Not Bouncy");
else if(isDecreasing(n)==true)
System.out.println("The number " + n + " is Decreasing and Not Bouncy");
else
System.out.println("The number " + n + " is bouncy");
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
BouncyNumber ob = new BouncyNumber();
System.out.print("Enter a number : ");
int n = sc.nextInt();
ob.isBouncy(n);
}
}
Output
Enter a number : 22344
The number 22344 is Increasing and Not Bouncy
Enter a number : 774410
The number 774410 is Decreasing and Not Bouncy
Enter a number : 155349
The number 155349 is bouncy