Google News
logo
Java Program to Autobiographical Number
An autobiographical number is a number where the digits in the number represent the number of times that digit occurs in the number itself.

For example, 1210 is an autobiographical number because it contains one 0, two 1s, and one 2.

Here's a Java program to check if a given number is autobiographical or not :
Program :
import java.util.Arrays;

public class AutobiographicalNumber {
    public static boolean isAutobiographical(int num) {
        String str = Integer.toString(num);
        int[] arr = new int[str.length()];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = str.charAt(i) - '0';
        }

        int[] count = new int[10];
        for (int i = 0; i < arr.length; i++) {
            count[arr[i]]++;
        }

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != count[i]) {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {
        int num = 1210;
        if (isAutobiographical(num)) {
            System.out.println(num + " is an autobiographical number");
        } else {
            System.out.println(num + " is not an autobiographical number");
        }
    }
}
Output :
1210 is an autobiographical number
The isAutobiographical() method takes an integer as input and checks if the number is an autobiographical number or not. The method first converts the integer into a string and then extracts the digits into an integer array.

It then uses another integer array to count the frequency of each digit in the original number.

Finally, it checks if the frequency of each digit matches the digit itself. If they match for all digits, the method returns true, indicating that the number is autobiographical. Otherwise, it returns false.

In the main method, we can pass any number to the isAutobiographical() method to check if it is an autobiographical number or not.