JZ31 整数中1出现的次数
本文最后更新于:2022年4月9日 中午
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: int NumberOf1Between1AndN_Solution(int n) { long digit = 1; int high = n / 10, cur = n % 10, low = 0; int res = 0; while (high != 0 || cur != 0) { if (cur == 0) { res += high * digit; } else if (cur == 1) { res += high * digit + low + 1; } else { res += (high + 1) * digit; } low += cur * digit; cur = high % 10; high /= 10; digit *= 10; } return res; } };
|