Topic:
Number 0 to n (inclusive) in number 2 appears several times.
Ideas:
1, violent methods, the number of each number contains a few 2, and then summed up.
2, Analysis: Consider the number of each digit n each occurrence 2 times, such as 123123;
Consider 4123123 from left to right;
Consider the first 1 (that is, the 6th digit), the number of occurrences of 2 is 4*10^6/10;
Consider the first 2 (that is, the 5th digit), the number of occurrences of 2 is 41*10^5/10+3123+1;
Consider the first 3 (that is, the 4th digit), the bit appears 2 times as (412+1) *10^4/10;
Attached: divided by 10 is the reason: every 10 digits, the probability that any bit appears 2 is 1/10.
Summary rule:
The number of occurrences of the first 2 is related to the digit in which the digit is located:
When the number of digit I is less than 2, the number of occurrences is equal to the number of the high part of the *10^I/10,
When the number of position I is equal to 2, the number of occurrences is equal to the number *10^i/10+n% (10^i) of the high part.
When the number of the first digit is greater than 2, the number of occurrences is equal to (the number + 1) *10^i/10 the high part.
Code:
#include <iostream>#include<sstream>#include<math.h>using namespacestd;template<classout_t,classIn_t>out_t Convert (ConstIn_t &t) {StringStream ss; out_t result; SS<<T; SS>>result; returnresult;}intCount2sinrangeatdigit (intNumberintBD) { intPowerof10=pow (Ten, D); intnextpowerof10=powerof10*Ten; intright=number%POWEROF10; introunddown=number-number%NEXTPOWEROF10; introundup=rounddown+NEXTPOWEROF10; intdigit= (NUMBER/POWEROF10)%Ten; if(digit<2) returnrounddown/Ten; Else if(digit==2) returnrounddown/Ten+right+1; Else returnroundup/Ten;}intCount2sinrange (intNumber ) { intCount=0; stringstr; STR=convert<string>(number); intlen=str.size (); for(intdigit=0;d igit<len;digit++) Count+=Count2sinrangeatdigit (number,digit); returncount;}intMain () {intN; while(cin>>N) {cout<<count2sinrange (n) <<Endl; } return 0;}
(algorithm) Number of occurrences of number 2 in integers from 0 to n