[LeetCode] Number of Digit One

353 查看

Problem

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.

Hint:

Beware of overflow.

Note

举个例子,分析1212个数中1的个数。

0 - 9:                             1(个位)
10 - 19:                10(十位) + 1(个位)
20 - 99:                           8(个位)
100 - 199:   100(百位) + 10(十位) + 10(个位)
200 - 999:              80(十位) + 80(个位)
1000 - 1199: 200(千位) + 120(同100 - 199)

到这里,看出规则了么?
前1000个数百位、十位、个位各有100个1,前100个数中个位,十位各有10个1,前10个数个位有1个1,那么不妨猜一猜前10000个数有多少个1?
4000.

下面分析一下计算过程:

首先,找哪些1?找这些1的顺序是什么?上面例子采用的是逐位计数法,先从个位算起,再算十位、百位上的1。

其次,确定了次序之后,怎么找这一位的1?对于个位的1,我们可以去计算n包含多少个10,每个10一定对应一个1,再加上0 ~ 9之间的一个1;对于十位的1,也就是计算10的个数,同理,先计算n包含多少个100,再加上n除以100的余数中包含10的个数,再加上0到100之间的那个10。

总结个位和百位的方法,都是先确定一个基数,base,再看对于每个base是否包含这一位的special case中的1(*11到19,110到119,1100到1199是specail case)。

只有大于左边界(10、110、1100)才部分包含,且只有大于右边界20、200的数(29, 150, 1300)才完整包含,这些special case中多余的1。

对于special case而言,部分包含余数做,完整包含进位后的商做。逐位向上累加,可得结果。千位万位,大致如此。

例如:

n = 1212

base = 1
q = 1212, r = 0
count += 122: 个位

base = 10
q = 121, r = 2
count += 120 + 3: 十位

base = 100
q = 12, r = 12
count += 200: 百位

base = 1000
q = 1, r = 212
count += 213: 千位

Solution

public class Solution {
    public int countDigitOne(int n) {
      int count = 0;
      for (long base = 1; base <= n; base *= 10) {
        long q = n/base, r = n%base;
        count += (q+8) / 10 * base + (q%10 == 1 ? r+1 : 0);
      }
      return count;
    }
}