April 19, 2022

Stable or Unstable Number Java Program

In this post we’ll see a Java program to check whether the number is stable or not. A stable number is a number in which each digit occurs the same number of time. For example 1010, 3355, 2020, 794479, in these numbers you can see that the frequency of each digit is same in the number.

An unstable number is a number in which each digit does not occur the same number of time, for example 1011, 3356, 404, 794419.

Check number Stable or Unstable Java Program

Create an array of length 10 for digits 0 to 9. This array is used to store frequency of each digit. In the while loop frequency of each digit is calculated and stored in the array.

When an integer array is created by default it will have 0 as value for each index. For some of the indices you will have values after calculating frequencies other will remain as 0. For example if 4422 is passed as number index 2 and 4 of the array will have value 2 all the other indices will have value 0.

In the for loop you discard all the elements with value as 0. Also a HashSet is used to store non-zero values. Note that HashSet stores only unique values so add() method of the HashSet returns false if same value is added again. This feature of the add() method of HashSet is used here; basically you have to check that the frequency of all the digits of the number is same if it is a stable number. So any time add() method returns true (after the first element is added) that means frequency is not same for all the digits thus an unstable number.

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class StableorUnstable {

  public static void main(String[] args) {
    System.out.println("Please enter a number : ");
    Scanner sc = new Scanner(System.in);
    int inputNum = sc.nextInt();
    boolean flag = isStable(inputNum);
    if(flag) {
      System.out.println(inputNum + " is a stable number");
    }else {
      System.out.println(inputNum + " is an unstable number");
    }
  }
	
  private static boolean isStable(int num) {
    int[] digitFreq = new int[10];
    int mod = 0;
    Set numSet = new HashSet<>();
    while(num != 0){
      mod = num % 10;
      digitFreq[mod]++;			
      num = num/10;
    }
    int firstAdd = 0;
    boolean addFlag;
    for(int i = 0; i < 9; i++) {
      // discard array elements with 0 values
      if(digitFreq[i] == 0)
        continue;
      firstAdd++;
      // if same number is added again add method returns false
      addFlag = numSet.add(digitFreq[i]);
      if(firstAdd > 1 && addFlag)
        return false;
    }
    return true;
  }
}
Output
Please enter a number : 
4422
4422 is a stable number

Please enter a number : 
794419
794419 is an unstable number

That's all for the topic Stable or Unstable Number Java Program. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment