Evaluate the number of 1 + 11 + 111 + 1111 +... + N 1 and how many 1?

Source: Internet
Author: User

Question: How many of the plus 1 + 11 + 111 + 1111 +... + N 1 and the middle 1?

Solution: Calculate from a single bit to the highest bit. For example, if the number is always increased to 2014 1, then a total of 2014 1 bits are added. First, judge the sum of the two bits (whether the single bit is 1 ), after the sum, the carry numbers are 201, of which 2, 0, and 1 correspond to the carry numbers of thousands, hundreds, and ten respectively. Then, the sum of the ten digits is 2013, and the first carry 1 is added, calculate the carry (compared to the ten-digit calculation result, only 20 in the single-digit calculation result is the carry value. In fact, 1 of the 201-digit calculation is used out of the ten-digit calculation, divide 201 by 10, which is the carry forward of the 10 digits), and so on.

The program code is as follows:

# Include <stdio. h> void sum1_compute (int n) {int sum; int carry_num = 0, Count = 0; while (n> 0) {sum = N + carry_num % 10; if (1 = sum % 10) Count ++; carry_num/= 10; carry_num + = sum/10; n --;} printf ("sum contains (1) % d. \ n ", count) ;}int main () {int N; printf (" Please input N: "); scanf (" % d ", & N ); sumatecompute (n );}

The result of running the program on Ubuntu is:

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.