import java.util.Scanner;
public class BouncyNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if (isBouncy(n)) {
System.out.println(n + " is a bouncy number.");
} else {
System.out.println(n + " is not a bouncy number.");
}
}
public static boolean isBouncy(int n) {
boolean increasing = false;
boolean decreasing = false;
int prevDigit = n % 10;
n /= 10;
while (n > 0) {
int currDigit = n % 10;
if (currDigit > prevDigit && decreasing) {
return true;
} else if (currDigit < prevDigit && increasing) {
return true;
}
if (currDigit < prevDigit) {
decreasing = true;
} else if (currDigit > prevDigit) {
increasing = true;
}
prevDigit = currDigit;
n /= 10;
}
return false;
}
}
Enter a number: 538
538 is a bouncy number.
Enter a number: 631
631 is not a bouncy number.
isBouncy()
function to check if the entered number is bouncy or not. The isBouncy()
function takes an integer argument and returns a boolean value indicating whether the number is bouncy or not.isBouncy()
function uses two boolean variables increasing and decreasing to keep track of whether the digits are increasing
or decreasing
. We then iterate through each digit of the number by repeatedly dividing it by 10 and taking the remainder. We compare the current digit to the previous digit and set the increasing
or decreasing
flag accordingly. true
. If we make it through the entire loop without finding a bouncy pattern, then the number is not bouncy and we return false
.