Leetcode-5010 Digit Count in Range(范围内的数字计数)

 1 class Solution
 2 {
 3     public:
 4         int count(int n, int x)
 5         {
 6             int cnt = 0, k;
 7             for (int i = 1; k = n / i; i *= 10)
 8             {
 9                 int high = k / 10;
10                 if (x == 0)
11                 {
12                     if (high)
13                     {
14                         high--;
15                     }
16                     else
17                     {
18                         break;
19                     }
20                 }
21                 cnt += high * i;
22                 int cur = k % 10;
23                 if (cur > x)
24                 {
25                     cnt += i;
26                 }
27                 else if (cur == x)
28                 {
29                     cnt += n - k * i + 1;
30                 }
31             }
32             return cnt;
33         }
34         int digitsCount(int d, int low, int high)
35         {
36             return count(high,d)-count(low-1,d);
37         }
38 };

参考:http://www.it610.com/article/4964533.htm

posted @ 2019-06-02 08:35  Asurudo  阅读(575)  评论(0编辑  收藏  举报