"Disclaimer: All rights reserved, please indicate the source of the reprint, do not use for commercial purposes. Contact mailbox: [Email protected] "
Topic Link:http://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6?rp=2&ru=/ta/coding-interviews& Qru=/ta/coding-interviews/question-ranking
Title Description
Find out the number of occurrences of 1 in an integer of 1~13, and calculate the number of occurrences of 1 in an integer of 100~1300? For that, he counted a few times. 1~13 contains 1 of the numbers are 1, 10, 11, 12, 13 so there is a total of 6, but for the latter problem he can not do. Acmer wants you to help him, and to make the problem more common, you can quickly find out the number of occurrences of 1 in any nonnegative integer interval.
Ideas
The law of programming beauty:
1. If the number of position I (from right to left, from 1 to the label) is 0, then the number of times I may appear 1 is determined by the higher (if there is no high, the high is 0), which equals the weighted 10^ (i-1) of the current digits of the higher digits X.
2. If the number on position I is 1, then the number of times I may appear in the position of 1 is not only affected by the higher level, but also by the low impact (if there is no low, as low as 0), equal to the higher digit x the current number of digits of the weight 10^ (i-1) + (low number + 1).
3. If the number on position I is greater than 1, then the number of times on the I position may be 1 at the higher level (if there is no high, as high as 0), equal to (higher digit + 1) x the weight of the current number of digits 10^ (i-1).
Class Solution{public:int numberof1between1andn_solution (int n) {int count =0;int i =1;int current =0,after =0,before =0;w Hile ((n/i)!=0) {current = (n/i)%10;before = n/(i *10), after = N-(n/i) * I;IF (current >1) Count = Count + (BES Fore + 1) * i;else if (current ==0) Count = Count + before * i;else if (current ==1) Count = Count + before * i + after +1;i = I *10;} return count;}};
Copyright NOTICE: This article is the original blogger article, if reproduced, please indicate the source
The number of occurrences in integer 1 of the "Offer of Swords" (1 occurrences from 1 to n integers)