The following is a program to count the number of k's between 0 to n. Where "k" is any number between 1 to 9 and n is any number greater than k.
{
public static void main(String[] args)
{
int k = 2;
int n = 1000;
System.out.println("Number of " + k + "'s between 0 to " + n + " is " + CountDigit.numOfKs(k, n));
}
public static int countK100(int k, int n)
{
if (n >= ((k + 1) * 10))
{
if (n % 10 == 0 || n % 10 < k)
{
return 10 + (n / 10);
}
if (n % 10 >= k)
{
return 10 + (n / 10) + 1;
}
}
if (n >= ((k) * 10) && n < ((k + 1) * 10))
{
if (n % 10 == 0 || n % 10 < k)
{
return (n % 10) + (n / 10) + 1;
}
if (n % 10 >= k)
{
return (n % 10) + (n / 10) + 2;
}
}
if (n < ((k) * 10))
{
if (n % 10 == 0 || n % 10 < k)
{
return (n / 10);
}
if (n % 10 >= k)
{
return (n / 10) + k;
}
}
return 0;
}
public static int countK(int k, int n)
{
if (n / 10 == 0)
{
if (n > k)
return 1;
else
return 0;
}
else if (n / 100 == 0)
{
return countK100(k, n);
}
else
{
int c = 10;
int g = 0;
while (n % c == 0)
{
g++;
c = c * 10;
}
c = c / 10;
int j = n / c;
if (j > k)
return c + (((c / 10) * g) * j);
else
return (((c / 10) * g) * j);
}
}
public static int numOfKs(int k, int n)
{
int c = 10;
int s = n;
int count = 0;
while (s != 0)
{
int m = s % c;
count = count + countK(k, m);
s = s - m;
c = c * 10;
}
return count;
}
}
Output: