My accepted c++ code


  • 0
    P
    class Solution {
    public:
        int countDigitOne(int n) {
            if(n <= 0)
                return 0;
            int  x = n;
            int y = 0;
            int res = 1;
            
            while(x >= 10)
            {
                res *= 10;
                x /= 10;
                ++y;
            }
            if(x == 1)
                return res / 10 * y +  n % res + 1 + countDigitOne(n % res);
            else
                return res / 10 * (n/res) * y +  res + countDigitOne(n % res);
             
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.