您的位置:首页 > 其它

[Leetcode 233, Medium] Number of Digit One

2015-08-03 03:49 375 查看
Problem:

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

For example:

Given n = 13,

Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

Hint:

Beware of overflow.

Analysis:

Solutions:

C++:

int countDigitOne(int n) 
    {
        int num = 0;
        if(n <= 0)
            return num;

        long long base = 10;
        if(n < base)
            return 1;

        for(; 10 * base <= n; base *= 10);

        if(n == base) {
            num = base / 10 + 10 * countDigitOne(base / 10- 1) + 1;
        } else if(n % base == 0) {
            num = base + (n / base) * countDigitOne(base - 1);
        } else if(n / base > 1) {
            num = base + (n / base) * countDigitOne(base - 1) + countDigitOne(n % base);
        } else {
            num = n % base + 1 + countDigitOne(base - 1) + countDigitOne(n % base);
        }

        return num;
    }
Java:

Python:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: