Given a number N, now find the number of occurrences of each digit 0..9 from 0 to N
Ex:
i/p: 12
o/p:
2
5
2
1
1
1
1
1
1
1
static int[] findOccurrences(int n){
if(n == 0) //Base condition
return null;
if(n < 0) //If number is negitive then make it positive.
n = n * (-1);
int []arr = new int[10]; //array to hold the occurrences of numbers
init(arr); //initialize the array with zero
arr[0]++;
for(int i = 1; i <= n; i++){ //loop till given number to find the occurrence
int temp = i;
while( temp > 0){ //find the occurrence of digit in current number - temp
int rem = temp % 10; //get the last digit of current number
arr[rem]++; //increment the count of digit
temp /= 10;
}
}
return arr; //return the array of occurrence of number
}
static void init(int []arr){
for(int i = 0; i < 10; i++)
arr[i] = 0;
}
public static void main(String... args){
int n = 12;
int []count = findOccurrences(n);
System.out.println(java.util.Arrays.toString(count));
}
}
Ex:
i/p: 12
o/p:
2
5
2
1
1
1
1
1
1
1
Implementation:
class GivenNumberN_FindTheNumberOfOccurrencesOfEachDigit{static int[] findOccurrences(int n){
if(n == 0) //Base condition
return null;
if(n < 0) //If number is negitive then make it positive.
n = n * (-1);
int []arr = new int[10]; //array to hold the occurrences of numbers
init(arr); //initialize the array with zero
arr[0]++;
for(int i = 1; i <= n; i++){ //loop till given number to find the occurrence
int temp = i;
while( temp > 0){ //find the occurrence of digit in current number - temp
int rem = temp % 10; //get the last digit of current number
arr[rem]++; //increment the count of digit
temp /= 10;
}
}
return arr; //return the array of occurrence of number
}
static void init(int []arr){
for(int i = 0; i < 10; i++)
arr[i] = 0;
}
public static void main(String... args){
int n = 12;
int []count = findOccurrences(n);
System.out.println(java.util.Arrays.toString(count));
}
}