In this tutorial, we will write an Autobiographical Number Program in Java and also learn what is Autobiographical Number.
Autobiographical Number
An autobiographical number is a number such that the first digit of it counts how many zeroes are there in it, the second digit counts how many ones are there, and so on. Basically, it counts the frequency of digits from 0 to 9 in order which they occur in a number.
Example: 1210 has 1 zero, 2 ones, 1 two, and 0 threes.
Some other examples include 2020, 21200, 3211000, 42101000, etc.
Explanation: Consider a number, 21200.
First, the sum of the digits: 2+1+2+0+0 = 5
Second, count the number of digits: 5
Since the sum of the digits is equal to the number of digits present in a number. Therefore, 21200 is an autobiographical number.
Java Program to check if the given number is Autobiographical Number or not
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | import java.util.*; public class AutobiographicalNumber { public static void main(String args[]) { int num, n; String str; boolean flag; Scanner sc = new Scanner(System.in); System.out.print("Enter the number: "); num = sc.nextInt(); num = Math.abs(num); n = num; str = String.valueOf(num); int digitarray[] = new int[str.length()]; for (int i = digitarray.length - 1; i >= 0; i--) { digitarray[i] = n % 10; n = n / 10; } flag = true; for (int i = 0; i < digitarray.length; i++) { int count = 0; for (int j = 0; j < digitarray.length; j++) { if (i == digitarray[j]) count++; } if (count != digitarray[i]) { flag = false; break; } } if (flag) System.out.println(num + " is an Autobiographical number."); else System.out.println(num + " is not an Autobiographical number."); } } |
Output:
//First Run
Enter the number: 1210
1210 is an Autobiographical number.
\\Second Run
Enter the number: 1410
1410 is not an Autobiographical number.