233. Number of Digit One

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

Example:

Input: 13
Output: 6 
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
class Solution {
public:
    /*int countDigitOne(int n) {
        if(n<=0) return 0;
        int sum = 0;
        for(int i=1; i<=n; i++)
            sum += NumOne(i);
        return sum;
    }
    
    int NumOne(int n)
    {
        int sum = 0;
        while(n)
        {
            if(n%10==1)
                sum++;
            n/=10;
        }
        return sum;
    }*/
    
    int countDigitOne(int n) {
        if(n<=0 ) return 0;
        string str = to_string(n);
        int first = str[0] - '0';
        int length = str.length();
        
        if(length==1&&first>0)
            return 1;
        
        int NumFirstDigit = 0;
        if(first>1)
        {
            NumFirstDigit = PowerBase10(length-1);
        }else if(first=1)
        {
            string tmp = str.substr(1);
            NumFirstDigit = atoi(tmp.c_str()) + 1;
        }
        

        int NumOtherDigit = first*(length-1)*PowerBase10(length-2);
        string tmp = str.substr(1);
        int NumRecursiveDigit = countDigitOne(atoi(tmp.c_str()));
        return NumFirstDigit + NumOtherDigit + NumRecursiveDigit;
        
    }
    
    int PowerBase10(unsigned int n)
    {
        int result = 1;
        for(int i=0; i<n; i++)
            result *= 10;
        return result;
    }
};


猜你喜欢

转载自blog.csdn.net/dongyu_1989/article/details/80415214
今日推荐