Number of occurrences in integer 1 (number of occurrences from 1 to n integers in 1)

Source: Internet
Author: User

Find out the number of occurrences of 1 in an integer of 1~13, and calculate the number of occurrences of 1 in an integer of 100~1300? For that, he counted a few times. 1~13 contains 1 of the numbers are 1, 10, 11, 12, 13 so there is a total of 6, but for the latter problem he can not do. Acmer wants you to help him, and to make the problem more common, you can quickly find out the number of occurrences of 1 in any nonnegative integer interval.

The simple way to do this is to follow the given bits to analyze

In the single digit appears 1 the number =n/10+ (single digit =0,0; digit >1,1; digit = 1, low 0 bit +1);

10 bits appear 1 =n/100*10+ (10 bit =0,0; 10 bits >1,10,; 10 bits = 1, low one +1);

Hundreds appear in the number of 1 =n/1000*100+ (hundred =0,0; hundred >1,100; hundred = 1, low two bits +1);

Wait a minute

The complexity of the algorithm is only related to the number of digits

Algorithm Description:

(1) The number of digits of a given positive integer A is calculated, assuming that the number of N,num holds 1

(2) another p=a,num+=p/10i*10i-1; (i=1...n-1);

(3) Order p=a/10i-1;p=p%10,if (P==1) num+=a%10i-1+1;if (p>1) num+=10i-1; (I=1....N)

(4) printf (num);

Manual solution:

125

Digit =12+1

10-bit =10+10

Hundred =0+26

59 x 1

12107:

Digit: 1210*1+1

10-bit: 121*10

Hundred: 12*100+8

Thousand: 1*1000+1000

Million-bit: 0+2108

10000:

1000+0

100*10+0

10*100+0

1*1000+0

0+1

1 classSolution {2  Public:3     intNumberof1between1andn_solution (intN)4     {5         Longm=0;6         intres=0;7          for(m=1; m<=n;m*=Ten){8             if(n/m%Ten==1)9res+=n%m+1;Ten             if(n/m%Ten>1) Oneres+=m; Ares+=n/m/Ten*m; -         } -         returnRes; the     } -};

Number of occurrences in integer 1 (number of occurrences from 1 to n integers in 1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.