C++ concise solution with explanation


  • -1
    A
    class Solution {
    public:
        int countDigitOne(int n) {
            if(n <= 0)
                return 0;
            int cur;  // current digit
            int high, low; // higher and lower number
            int cnt = 0;
            long long ifactor = 1;
            while(n / ifactor != 0)
            {
                cur = (n / ifactor) % 10;
                high = n / (ifactor * 10);
                low = n - (n / ifactor) * ifactor;
                if(cur == 1)
                {
                    cnt += high*ifactor + low + 1;
                }
                else if(cur == 0)
                {
                    cnt += high*ifactor;
                }
                else
                    cnt += (high+1)*ifactor;
                ifactor*=10;
            }
            return cnt;
        }
    };

Log in to reply
 

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