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