Optimized way to count number of occurrences of a digit in a range of numbers [duplicate]
Here is a simple implementation that uses modulus. If you want a faster code, you will need to find some smart formula that gives you the result without performing the actual computation.
import java.util.Arrays;
public class Counter
{
private static long[] counts = new long[10];
public static void count(long x, long y)
{
Arrays.fill(counts, 0);
for(long val=x; val<=y; val++)
count(val);
}
public static void count(long val)
{
while(val>0)
{
int digit = (int)(val % 10);
counts[digit]++;
val /= 10;
}
}
public static void main(String[] args)
{
count(1, 20);
System.out.println(Arrays.toString(counts));
}
}
Output:
[2, 12, 3, 2, 2, 2, 2, 2, 2, 2]