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.

方法一

 1 class Solution {
 2 public:
 3     int countDigitOne(int n) {
 4         int cnt=0;
 5         for(long long m=1;m<=n;m*=10)
 6         {
 7             int a=n/m,b=n%m;
 8             if(a%10==0)
 9                 cnt+=a/10*m;
10             else if(a%10==1)
11                 cnt+=a/10*m+(b+1);
12             else
13                 cnt+=(a/10+1)*m;
14         }
15         return cnt;
16     }
17 };

方法二

1 class Solution {
2 public:
3     int countDigitOne(int n) {
4         int cnt=0;
5         for(long long m=1;m<=n;m*=10)
6             cnt=cnt+(n/m+8)/10*m+(n/m%10==1)*(n%m+1);
7         return cnt;
8     }
9 };

 

相关文章:

  • 2021-10-15
  • 2021-08-20
  • 2022-12-23
  • 2021-12-27
  • 2021-12-01
  • 2022-12-23
  • 2021-08-31
猜你喜欢
  • 2021-10-11
  • 2022-01-04
  • 2021-05-26
  • 2022-12-23
  • 2022-12-23
  • 2022-01-03
  • 2022-12-23
相关资源
相似解决方案