[LeetCode] Number of Digit One
Posted immjc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Number of Digit One相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode(191):Number of 1 Bits
Leetcode 200. Number of Islands
LeetCode 191. Number of 1 Bits
LeetCode191 Number of 1 Bits. LeetCode231 Power of Two. LeetCode342 Power of Four