Evaluate the number of times 1 appears in the decimal representation of the n integers from 1 to n

Source: Internet
Author: User

Question:

Enter an integer n to calculate the number of times 1 appears in the decimal representation of the n integers from 1 to n. The efficiency is as high as possible.

For example:

F (2) = 1

F (12) = 5

F (20) = 12

F (115) = 44


Solution:

The simplest method is to process from 1 to n cyclically, calculate the number of 1 in each number, and accumulate it. This is very inefficient.

The second method is to accumulate the number of digits from 1 to n, such as 10 digits and hundreds of digits. The number of 32-bit integer operations cannot exceed 10 times.

Int numberof1 (int n) {int sum = 0; int factor = 1; int n2 = n; // remainder of n/[1 | 10 | 100 | 1000 |...] // The remainder of n % 1, n % 10, n % 100, n % 1000 int remainder = 0; while (n2> 0) {// variable num is number of 1 in place of units, from 1 to n2 // The variable num indicates the number of 1 in one from 1 to n2 int num = (n2 + 9)/10; // variable true_num is number of 1 in place of units/tens/hundreds/thousands /... (place is determined by factor), from 1 to n // variable true _ Num indicates the number of 1 values (single/ten/hundred/thousands/...) corresponding to the factor (1/10/100/1000/...) from 1 to n. // The complexity is here. For n, if this bit is 1, special processing is required. Int true_num; if (n2% 10 = 1) {true_num = (num-1) * factor + remainder + 1;} else {true_num = num * factor;} sum + = true_num; n2/= 10; factor * = 10; remainder = n % factor;} return sum ;}

You can manually check, or use the secure but inefficient method. I checked it manually and it should be okay.



Related Article

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.