1~n整数中出现1的次数

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

例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。

示例 1:

输入:n = 12
输出:5

示例 2:

输入:n = 13
输出:6

解法:

 

 1 public int countDigitOne(int n) {
 2         int high=n/10,low=0,cur=n%10,res=0,digit=1;
 3 
 4         while(high!=0||cur!=0){
 5             if(cur==0){
 6                 res+=high*digit;
 7             }else if(cur==1){
 8                 res+=high*digit+low+1;
 9             }else{
10                 res+=high*digit+digit;
11             }
12              low+=cur*digit;
13              cur=high%10;
14             digit*=10;
15             high/=10;
16                       
17         }
18         return res;
19     }

 

posted @ 2020-08-12 11:45  王余阳  阅读(292)  评论(0)    收藏  举报