Title Description
Solving a problem: induction
1 / ** 2 number 1 appears on the * bits are: n-/ 10 * 1+ (n-10 = 0% 1:!? 0) . 3 the number appearing on ten * 1: (n / 100 ) * 10 + (IF (K>. 19) 10 the else IF (K <10) the else K 0 - 10 + 1) . 4 * 1 appears on the number of one hundred of: (n / 1000) * 100 + (if ( K> 199) 100 the else IF (K <100) the else 0 K - 1 + 100) . 5 * i that is calculated where the bits 1, i = 1, number 1 indicates a calculated number of bits, 10 denotes a computing ten the number of bits 1 . 6 *% n-K = (I * 10) . 7 * COUNT (I) = (n-/ (10 * I)) + I * (IF (K> I * 2 - 1) I the else IF (K <I) 0 the else k - i + 1) . 8 * can be simplified so that the second half, we do not calculate i * 2 - 1, we only need to ensure k - i + 1 in the [0, i ] on the line interval, the last half of this can be written . 9 * min (max (I + K-1,0), I) => min (max ((n-MOD (I 10 *)) -. 1 + I, 0), I) 10 * / . 11 public static int NumberOf1Between1AndN_Solution(int n) { 12 if(n <= 0) { 13 return 0; 14 } 15 int count = 0; 16 for(long i = 1; i <= n; i *= 10){ 17 long diviver = i * 10; 18 count += (n / diviver) * i + Math.min(Math.max(n % diviver - i + 1, 0), i); 19 } 20 return count;
1 public static int NumberOf1Between1AndN_Solution01(int n) { 2 int count=0; 3 StringBuffer s=new StringBuffer(); 4 for(int i=1;i<n+1;i++){ 5 s.append(i); 6 } 7 String str=s.toString(); 8 for(int i=0;i<str.length();i++){ 9 if(str.charAt(i)=='1'){ 10 count++; 11 } 12 } 13 return count; 14 }
1 / * 2 * n, only the m-th bit is to be calculated when a suffix is a suffix calculated (n / m% 10 == 1) * (B + 1), . 3 * i.e. (n / m% 10 == 1) determining whether the m-th bit is 1, if it is 1, then the plus (b + 1), if 1, only the prefix is calculated. 4 * (2 if the number of calculations can be changed (n / m% 10 == 2) * (B +. 1), . 5 * 3 if the number of calculations can be changed to (n / m% 10 == 3) * (b + 1) ... and so on) . 6 * / . 7 public static int NumberOf1Between1AndN_Solution02 ( int n-) { . 8 int ones = 0 ; . 9 for ( int m =. 1; m <= n-; m * = 10 ) { 10 // one by one to obtain the values of m bits each . 11 int a = n-/ m; 12 is int B = n-% m; 13 if(a % 10 == 1){ 14 ones += (a + 8) / 10 * m +b + 1; 15 }else { 16 ones += (a + 8) / 10 * m; 17 } 18 } 19 return ones; 20 }
test:
1 public static void main(String[] args) { 2 int n=13; 3 int number = NumberOf1Between1AndN_Solution(n); 4 System.out.println(number); 5 } 6 输出:6