LeetCode 233 Number of Digit One 某一范围内的整数包含1的数量

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 };
原文地址:https://www.cnblogs.com/xidian2014/p/8541843.html