233 Number of Digit One

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.

输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。

C++:

 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             int a = n/m ;
 7             int b = n%m ;
 8             cnt += (a+8)/10 * m + ((a%10 == 1) ? b+1 : 0) ;
 9         }
10         return cnt ;
11     }
12 };
原文地址:https://www.cnblogs.com/mengchunchen/p/9004222.html