# Programming Algorithm-code for the number of times 1 appears in an integer from 1 to n (C)

Source: Internet
Author: User

Code for the number of times 1 appears in an integer from 1 to n (C)

Address: http://blog.csdn.net/caroline_wendy

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.

Split it into the highest digit, the other digits, and finally solve the number.

21345-> 1346-21345 [10000-19999, maximum bit + 1346-x1345 remaining digits] + 1-1345;

Code:

```/** Main. cpp ** Created on: June 29, 2014 * Author: wang */# include

# Include

# Include

# Include

Using namespace std; int PowerBase10 (size_t n) {int result = 1; for (size_t I = 0; I

'9' | * strN = '\ n') return 0; int first = * strN-'0'; size_t length = strlen (strN ); if (length = 1 & first = 0) return 0; if (length = 1 & first> 0) return 1; // The highest digit int numFirstDight = 0; if (first> 1) numFirstDight = PowerBase10 (length-1); else if (first = 1) numFirstDight = atoi (strN + 1) + 1; // + 1 remove the highest bit, and Add 1 // other digits int numOtherDights = first * (length-1) * PowerBase10 (length-2 ); // The last remaining int numRecursive = NumberOf1 (strN + 1); return numFirstDight + numOtherDights + numRecursive;} int NumberOf1Between1AndN (int n) {if (n <= 0) return 0; char strN [50]; sprintf (strN, "% d", n); return NumberOf1 (strN);} int main (void) {int result = NumberOf1Between1AndN (12 ); printf ("result = % d \ n", result); return 0 ;}

```

Output:

`result = 5`

Related Keywords:
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.