力扣链接:
https://leetcode.cn/problems/...
解题思路:
- 找法则
从个位数开始,依照以后位将数字分成右边high局部,左边low局部,以后位的数字分为三种类型:
(1)0: res = high * digit;
(2)1: res = high * digit + low + 1;
(3)2/.../9: res = (high + 1) * digit;
class Solution{ public: int countDigitOne(int n) { // 参数判断 if (n < 1) { return 0; } // 从个位数开始 long digit = 1; int high = n / 10, low = 0, cur = n % 10; int res = 0; while(cur != 0 || high != 0) { if (cur == 0) { res += high * digit; } else if (cur == 1) { res += high * digit + low + 1; } else { res += (high + 1) * digit; } low += cur * digit; high = high / 10; cur = high % 10; digit *= 10; } return res; }};