leetcode 233. 数字1的个数(Number of Digit One)

             **题目为:**

给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。
示例:输入: 13
输出: 6
解释: 数字 1 出现在以下数字中: 1, 10, 11, 12, 13 。
遇到一个解法,简短而有效。
附上链接 https://www.2cto.com/kf/201507/415690.html
class Solution { public: int countDigitOne(int n) { int ones = 0; for (long m = 1; m <= n; m *= 10) { long a = n/m, b = n%m; ones += (a + 8) / 10 * m; if(a % 10 == 1) ones += b + 1; } return ones; } };

猜你喜欢

转载自blog.csdn.net/weixin_42060918/article/details/85543101
今日推荐