原题地址:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/
题目描述:
解题方案:
参考了题解,自己虽然也能想出来但是思路很乱。递归的话返回值是把n分块考虑了。分为除去最高位后面的部分和加上最高位的部分,再加上最高位,分类讨论。
代码:
class Solution {
public int countDigitOne(int n) {
return dfs(n);
}
public int dfs(int n)
{
if(n <= 0) return 0;
String num = String.valueOf(n);
int high = num.charAt(0) - '0';
int pow = (int)Math.pow(10, num.length() - 1);
int last = n - high*pow;
if(high == 1)
return dfs(pow - 1) + dfs(last) + last + 1;
// 先考虑1 ~ pow-1中所有的1的个数
// 再考虑pow ~ n中除去最高位部分的1,再加上最高位的1
return high * dfs(pow - 1) + pow + dfs(last);
// 除去最高位的所有的最高位不是1的数中包含的1
//加上最高位的1,加上最高位为high的所有数中的1
}
}