码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Number of Digit One

时间:2018-05-23 22:12:36      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:for   1出现的次数   lse   等于   AC   leetcode   weight   ret   integer   

 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.

1~n中1出现的次数

令当前位数为weight。当前位数的高位为round。当前位数的低位为former

个位:(base=1)

个位大于0:round * base + base

个位等于0:round * base

十位:(base=10)

十位大于1:round * base + base

十位等于1:round * base + former + 1

十位等于0:round * base

高位同十位

参考代码如下

class Solution {
public:
    int countDigitOne(int n) {
        if (n < 1)
            return 0;
        int count = 0;
        int a = n, b = 0;
        int base = 1;
        while (a)
        {
            b = a % 10;
            a /= 10;
            count += a * base;
            if (b > 1)
                count += base;
            else if (b == 1)
                count += (n % base) + 1;
            base *= 10;
        }
        return count;
    }
};

 

[LeetCode] Number of Digit One

标签:for   1出现的次数   lse   等于   AC   leetcode   weight   ret   integer   

原文地址:https://www.cnblogs.com/immjc/p/9079465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!