求出113的整數中1出現的次數,並算出1001300的整數中1出現的次數?爲此他特別數了一下1~13中包含1的數字有1、10、
11、12、13因此共出現6次,但是對於後面問題他就沒轍了。ACMer希望你們幫幫他,並把問題更加普遍化,可以很快的求出任意
非負整數區間中1出現的次數(從1 到 n 中1出現的次數)。
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
int tmp=0;
for (int i = 0; i <=n; i++) {
int j = i;
String s = String.valueOf(j);
int l=s.length();
while (l>0) {
int x = (int) Math.pow(10, l - 1);
int y = j/ x;
if (y == 1) {
tmp++;
}
j= j % x;
l--;
}
}
return tmp;
}
}
比較笨的辦法。