Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
[思路]
reference: https://leetcode.com/discuss/44281/4-lines-o-log-n-c-java-python
intuitive: 每10個數, 有一個個位是1, 每100個數, 有10個十位是1, 每1000個數, 有100個百位是1. 做一個循環, 每次計算單個位上1得總個數(個位,十位, 百位).
例子:
以算百位上1為例子: 假設百位上是0, 1, 和 >=2 三種情況:
case 1: n=3141092, a= 31410, b=92. 計算百位上1的個數應該為 3141 *100 次.
case 2: n=3141192, a= 31411, b=92. 計算百位上1的個數應該為 3141 *100 + (92+1) 次.
case 3: n=3141592, a= 31415, b=92. 計算百位上1的個數應該為 (3141+1) *100 次.
以上三種情況可以用 一個公式概括:
(a + 8) / 10 * m + (a % 10 == 1) * (b + 1);
[CODE]
public 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; } }