标签:for 1出现的次数 lse 等于 AC leetcode weight ret integer
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