解决方法:先计算出最大位,即个、十、百、千、万,然后分别除以万、千、百,得到整数部分,即得到每一个数字,然后比较相加;
代码如下:
public class Solution {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner in=new Scanner(System.in);
int k,n;
System.out.print("k: ");
k = in.nextInt();
System.out.print("n: ");
n = in.nextInt();
int count = digitCounts(k,n);
System.out.println(count);
in.close();
}
public static int digitCounts(int k, int n) { // k = 1 n = 1234
// write your code here
int count=0,type = 1,x,y;
if(k == 0)count++;
for(int i = 0;i<=n;i++)
{
type = 1;
while(i>type) //i=10
{
type = type*10;
}
if(i!=type)
type = type/10;
y = i;
while(type!=0)
{
//System.out.print("i:"+i);
x = y/type;
//System.out.print(" x:"+x);
y = y%type;
//System.out.print(" y:"+y);
if(x == k) count ++;
//System.out.print(" count:"+count);
type = type/10;
//System.out.println("");
}
}
return count;
}
}