链接:https://www.nowcoder.com/questionTerminal/bd7f978302044eee894445e244c7eee6
来源:牛客网
参考博文:http://www.cnblogs.com/nailperry/p/4752987.html,主要就是从数字出发找规律。
一、1的数目
编程之美上给出的规律:
-
如果第i位(自右至左,从1开始标号)上的数字为0,则第i位可能出现1的次数由更高位决定(若没有高位,视高位为0),等于更高位数字X当前位数的权重10i-1。
-
如果第i位上的数字为1,则第i位上可能出现1的次数不仅受更高位影响,还受低位影响(若没有低位,视低位为0),等于更高位数字X当前位数的权重10i-1+(低位数字+1)。
-
如果第i位上的数字大于1,则第i位上可能出现1的次数仅由更高位决定(若没有高位,视高位为0),等于(更高位数字+1)X当前位数的权重10i-1。
上代码
链接:https://www.nowcoder.com/questionTerminal/bd7f978302044eee894445e244c7eee6
来源:牛客网
/**
- @param n
- @param x [1,9]
- @return
/
public int NumberOfXBetween1AndN_Solution(int n,int x) {
if(n<0||x<1||x>9)
return 0;
int high,low,curr,tmp,i = 1;
high = n;
int total = 0;
while(high!=0){
high = n/(int)Math.pow(10, i);// 获取第i位的高位
tmp = n%(int)Math.pow(10, i);
curr = tmp/(int)Math.pow(10, i-1);// 获取第i位
low = tmp%(int)Math.pow(10, i-1);// 获取第i位的低位
if(curr==x){
total+= high(int)Math.pow(10, i-1)+low+1;
}else if(curr<x){
total+=high*(int)Math.pow(10, i-1);
}else{
total+=(high+1)*(int)Math.pow(10, i-1);
}
i++;
}
return total;
}