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.

 

 1 public class Solution {
 2     static int[] sta;
 3     public int countDigitOne(int n) {
 4         if(n<=0) return 0;
 5         int result = calOnes(n);
 6         return result;
 7         
 8     }
 9     
10     //计算位数
11     public int totalPos(int n){
12         int count = 0;
13         while(n>0){
14             count++;
15             n /= 10;
16         }
17         return count;
18     }
19     //计算10的n次方
20     public int times(int n){
21         int result = 1;
22         while(n>0){
23             result *= 10;
24             n--;
25         }
26         return result;
27     }
28     //计算n位数最大值以内的所有数有多少个1,存在sta[n]中
29     public void cal(int len){
30         for(int i=1; i<=len; i++){
31             sta[i] = times(i-1) + 10*sta[i-1];
32         }
33         
34     }
35     //计算1的个数
36     public int calOnes(int n){
37         int count = totalPos(n);
38         sta = new int[count+1];
39         
40         cal(count);
41         
42         int result = 0;
43         int x=count;
44         int i = 0;
45         int hPos = 0;
46         int rest = n;
47         while(x>0){
48             hPos = rest/times(x-1);
49             rest = rest%times(x-1);
50             for(i=0; i<hPos; i++){
51                 if(i==1){
52                     result += (times(x-1) + sta[x-1]);
53                 }else{
54                     result += sta[x-1];
55                 }
56             }
57             if(hPos!=0 && i==1) result += (rest+1);
58             if(rest>0) x--;
59             else x=0;
60         }
61         
62         return result;
63     }
64 }

 

posted @ 2015-09-15 14:49  CHEN0958  阅读(158)  评论(0编辑  收藏  举报