leetcode 日经贴,Cpp code -Number of Digit One

Number of Digit One


class Solution {
public:
    int countDigitOne(int n) {
        if (n <= 0) return 0;
        vector<int> vi;
        while (n) {
            vi.push_back(n % 10);
            n /= 10;
        }
        reverse(vi.begin(), vi.end());
        int a = 0, b = 0, lenvi = vi.size();
        int ret = 0;
        for (int i = 0; i < lenvi; ++i) {
            int powerb = 1;
            b = 0;
            for (int j = i + 1; j < lenvi; ++j) {
                powerb *= 10;
                b = b * 10 + vi[j];
            }
            if (vi[i] > 1) {
                ret += (a + 1) * powerb;
            } else if (vi[i] == 1) {
                ret += a * powerb + b + 1;
            } else {
                ret += a * powerb;
            }
            a = a * 10 + vi[i];
        }
        return ret;
    }
};


class Solution {
public:
    int countDigitOne(int n) {
        if (n <= 0) {
            return 0;
        }
        int count1s = 0;
        vector<int> digits;
        while (n) {
            digits.push_back(n % 10);
            n /= 10;
        }
        int sz = digits.size();
        vector<int> pow10(sz), lowval(sz);
        pow10[0] = 1;
        lowval[0] = 0;
        for (int i = 1; i < digits.size(); ++i) {
            pow10[i] = pow10[i - 1] * 10;
            lowval[i] = lowval[i - 1] + digits[i - 1] * pow10[i - 1];
        }
        int highval = 0;
        for (int i = sz - 1; i >= 0; --i) {
            if (digits[i] > 1) {
                count1s += (highval + 1) * pow10[i];
            } else if (digits[i] == 1) {
                count1s += highval * pow10[i] + lowval[i] + 1;
            } else {
                count1s += highval * pow10[i];
            }
            highval = highval * 10 + digits[i];
        }
        return count1s;
    }
};


 
阅读更多
个人分类: 算法 leetcode Cpp
上一篇银子交易
下一篇leetcode 日经贴,Cpp code -Palindrome Linked List
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭