-
题目描述
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Example:
Input: 13
Output: 6
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. -
思路分析
- 暴力法:对10求余,判断个位是否为1,然后除10依次判断//会超时
- 优化:总结n每位数的规律,以n=123为例(1的个数:count; 当前位数上的权重:weight;
当前位数上的数字:now; 上一位数:last,例如按照从右到左,2的上一位数为3;循环次数:round)
个位数:3属于大于等于1,第十三个循环开始,则count = round + 1 = 12 + 1;
若为120,即now为小于1,开始第十三个循环,则count = round = 12;
十位数及以上位数:以十位数为例,2大于1,则count = round*weight + weight=1 * 10+10
若为11X,即now为1,则count = round * weight + 1+last=1 * 10 + 1 + x
若为10X,即now等于0,则count=round * weight=1 * 10
- 代码
class Solution {
public int countDigitOne(int n) {
if(n<1){
return 0;
}
int count = 0;
int round = n;
int weight =1;
int now = 0;
while(round>0){
now = round%10;
round = round/10;
if(now == 1){
count = count + (n%weight) + 1;
}
else if(now >1){
count =count +weight;
}
count = count + round*weigght;
weight = weight*10;
}
return count;
}
}