关闭

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

317人阅读 评论(0) 收藏 举报
分类:

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;
    }
};


 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:58410次
    • 积分:3062
    • 等级:
    • 排名:第11362名
    • 原创:260篇
    • 转载:8篇
    • 译文:0篇
    • 评论:4条
    文章分类
    最新评论