面试题43. 1~n整数中1出现的次数

输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。

例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。

 

示例 1:

输入:n = 12
输出:5
示例 2:

输入:n = 13
输出:6
 

限制:

1 <= n < 2^31

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

思路:

递归。

将数字分为最高位和后几位。

当数字由1开头时,数字分为1和后面的n-1位数,分别计算其中‘1’的个数。

如n=1234,high=1,pow=1000,last=234

f(n)=f(pow-1) + last + 1 + f(last);

当数字由2-9开头时,一样分为首位和其他n-1位数。

如n=3234,high=3,pow=1000,last=234

f(n)=pow + high*f(pow-1) + f(last);

代码:

class Solution {
    public int countDigitOne(int n) {
        return f(n);
    }
    private int f(int n ) {
        if (n <= 0)
            return 0;
        String s = String.valueOf(n);
        int high = s.charAt(0) - '0';
        int pow = (int) Math.pow(10, s.length()-1);
        int last = n - high*pow;
        if (high == 1) {
            return f(pow-1) + last + 1 + f(last);
        } else {
            return pow + high*f(pow-1) + f(last);
        }
    }
}

 

posted @ 2020-03-29 19:18  zjcfrancis  阅读(175)  评论(0编辑  收藏  举报