Number of occurrences of 1 in integers from 1 to n - Sword finger offer Java

Posted by cdickson on Fri, 25 Oct 2019 18:32:23 +0200

Title Description

Find out the number of times 1 appears in integers from 1 to 13, and find out the number of times 1 appears in integers from 100 to 1300. For this reason, he specially counted 1, 10, 11, 12 and 13 included in 1-13, so there were 6 times, but he had no idea about the following problems. ACMer wants you to help him and generalize the problem. You can quickly find the number of occurrences of 1 in any nonnegative integer interval (from 1 to 1 in n).

Solutions:

To find the number of 1, you need to know that the number increases by 0-9, and then every time you increase 0-9, there will be a 1. In the process of increase, the number of 1 appears, that is, 1 - the number of 1 in this number

For example, the number of 534, 1 is: number of bits 1 + number of tens 1 + number of hundreds 1 = (53 * 1 + 1) + (5 * 10 + 10) + (0 * 100 + 100) = 214

For details, please refer to: https://blog.csdn.net/yi'only/article/details/52012593

Native test code:

  1. package pratice714;
  2. public class num1ofInt714 {
  3.     public static int NumberOf1Between1AndN_Solution(int n) {
  4.         int count = 0;
  5.         for(int i=1;i<=n;i*=10)
  6.         {
  7.             int a = n/i; int b = n%i;
  8.             System.out.println("a: "+a+" ");
  9.             System.out.println("b: "+b+" ");
  10.             count += (a+8) / 10 * i + ((a % 10 == 1)? b + 1 : 0);
  11.             System.out.println("count: "+count+" ");
  12.         }
  13.         return count;
  14.     }
  15. //https://blog.csdn.net/yi_Afly/article/details/52012593
  16.     public static int NumberOf1Between1AndN_Solution2(int n) {        
  17.         if(n<1) return 0;
  18.         int count = 0; int base = 1; int round = n;
  19.         while(round>0)
  20.         {
  21.             int weight = round%10; //Current number of digits
  22.             round /= 10; //Prepare for next operation
  23.             count += round * base; //The first few bits are multiplied by base, and base represents the current number of bits, 10 bits * 10, and 100 bits * 100.
  24.             if(weight == 1)
  25.                 count += (n%base) + 1;
  26.             else if(weight > 1)
  27.                 count += base;
  28.             base *= 10;
  29.         }
  30.         return count;
  31.     }
  32.     public static void main(String[] args) {
  33.         int data = 13;
  34.         int result = NumberOf1Between1AndN_Solution(data);
  35.         System.out.print("result: "+result+" ");
  36.         
  37.         int result2 = NumberOf1Between1AndN_Solution2(data);
  38.         System.out.print("result: "+result2+" ");
  39.     }
  40. }

Scan code and pay attention to learning together anytime and anywhere!!! Just attack the lions with onions, more exciting, waiting for you!!