Calculate the numbers in the natural number sequence 1 and 2

Source: Internet
Author: User

Calculate the numbers in the natural number sequence 1 and 2

Problem:

Given a natural number N, calculate the numbers of 1 and 2 in 1, 2, 3... N. For example, 1, 2, 3... 10, appear 3 times, 1, 2, 3... 12, appear 7 times in total.

Ideas:

For example, to calculate 54321, you can calculate 50000 first, and then calculate the numbers of 1 and 2 in 4321-54321. The latter can be regarded as the number of 1 and 2 in, which simplifies the problem. When we calculate 50000, we can calculate the number of 1 and 2 in 49999, and recursively convert it into a known solution, add the number of 1 and 2 represented by 50000 (0 ).


Def count_from_number (number): if number <10: if number = 0: return 0 elif number = 1: return 1 else: return 2 number_str = str (number) first = number_str [0] left = number_str [1:] head = first + len (left) * '0' count = 0 count + = count_head (int (head )) if first = '1' or first = '2': count + = (number-int (head) count + = count_from_number (int (left )) return count // This method calculates the numbers def count_head (number): number_str = str (number) in numbers 1 and 2 ending with 0, 1000) first = number_str [0] count = 0 if first = '1' or first = '2': count + = 1 count + = count_from_number (number-1) return count number = 10 print ("count 1 or 2 for % d" % number) print ("result: % d" % count_from_number (number )) number = 12 print ("count 1 or 2 for % d" % number) print ("result: % d" % count_from_number (number )) number = 122 print ("count 1 or 2 for % d" % number) print ("result: % d" % count_from_number (number ))


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.