题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。
——来源于《剑指offer》
- 代码实现
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
if (n <= 0) {
return 0;
}
return getNums(String.valueOf(n));
}
private int getNums(String s) {
int length = s.length();
if (s == null || length <= 0) {
return 0;
} else if (length == 1) {
return Integer.parseInt(s) >= 1 ? 1 : 0;
}
int num = 0;
int one = Integer.parseInt(s.charAt(0) + "");
if (one > 1) {
num = (int) Math.pow(10, length - 1);
} else if (one == 1) {
num = Integer.parseInt(s.substring(1)) + 1;
}
int behind = (int) (Math.pow(10, length - 2) * one * (length - 1));
int front = getNums(s.substring(1));
return num + front + behind;
}
}