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:
- package pratice714;
- public class num1ofInt714 {
- public static int NumberOf1Between1AndN_Solution(int n) {
- int count = 0;
- for(int i=1;i<=n;i*=10)
- {
- int a = n/i; int b = n%i;
- System.out.println("a: "+a+" ");
- System.out.println("b: "+b+" ");
- count += (a+8) / 10 * i + ((a % 10 == 1)? b + 1 : 0);
- System.out.println("count: "+count+" ");
- }
- return count;
- }
- //https://blog.csdn.net/yi_Afly/article/details/52012593
- public static int NumberOf1Between1AndN_Solution2(int n) {
- if(n<1) return 0;
- int count = 0; int base = 1; int round = n;
- while(round>0)
- {
- int weight = round%10; //Current number of digits
- round /= 10; //Prepare for next operation
- 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.
- if(weight == 1)
- count += (n%base) + 1;
- else if(weight > 1)
- count += base;
- base *= 10;
- }
- return count;
- }
- public static void main(String[] args) {
- int data = 13;
- int result = NumberOf1Between1AndN_Solution(data);
- System.out.print("result: "+result+" ");
- int result2 = NumberOf1Between1AndN_Solution2(data);
- System.out.print("result: "+result2+" ");
- }
- }
Scan code and pay attention to learning together anytime and anywhere!!! Just attack the lions with onions, more exciting, waiting for you!!