题目
输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
分析
代码
public class Solution {
public static void main(String[] args) {
System.out.println(countDigitOne(12));
}
/**
* 1~n整数中1出现的次数
* @param n
* @return 1出现的次数
*/
public static int countDigitOne(int n) {
int count = 0;
String value = n+"";
for (int j = 1; j <= n; j++){
for (int i = 0; i < value.length(); i++){
int temp = (int) (j / (Math.pow(10,i)) % 10);
if (temp == 1) {
count++;
}
}
}
return count;
}
}
分析
代码
public class Solution {
public static void main(String[] args) {
System.out.println(countDigitOne(12));
}
public static int countDigitOne(int n) {
long cur = 1; //位因子
int count = 0;
while ( cur <= n){
int high = (int) (n / (cur * 10));//高位
int low = (int) (n - (n / cur) * cur);//低位
int current = (int) ((n / cur) % 10);//当前位
if (current == 0){
count = (int) (count + high * cur);
}else if (current == 1){
count = (int) (count + high * cur + low + 1);
}else {
count = (int) (count + (high + 1) * cur);
}
cur = cur * 10;
}
return count;
}
}
在剑指offer上看到了一种递归方法,但是有的地方感觉自己没理解了,水平有限啊,希望懂那种方法的道友给我指点下迷津,谢谢。