title: Enter an integer n to find the number of decimal representations of the n integers from 1 to n in 1 occurrences. For example, input 12, from 1 to 12 of these integers contain 1 of the numbers that have 1,10,11 and 12 appear altogether 5 times. a solution that does not consider time efficiency:
1 intNUMBEROF1BETWEEN1ANDN (unsignedintN)2 {3 intNumber=0;4 for(unsignedintI=1; i<=n;++i)5Number + =NumberOf1 (i);6 returnNumber ;7 }8 intNUMBEROF1 (unsignedintN)9 {Ten intNumber=0; One while(n) A { - if(n%Ten==1) -number++; then=n/Ten; - } - returnNumber ; -}
From the digital law to improve the time efficiency significantly:
1 intNUMBEROF1BETWEEN1ANDN (intN)2 {3 if(n<=0)4 return 0;5 Charstrn[ -];6sprintf (StrN,"%d", n);//convert an integer to a string7 returnNumberOf1 (StrN);8 }9 Ten intNUMBEROF1 (Const Char*StrN) One { A if(!strn| | *strn<'0'|| *strn>'9'|| *strn==' /') - return 0; - intfirst=*strn-'0'; theUnsignedintlength=static_cast<unsignedint>(strlen (StrN)); - if(length==1&&first==0) - return 0; - if(length==1&&first>0) + return 1; - + intnumfirstdigit=0; A if(first>1) atNumberfirstdigit=powerbase10 (length-1); - Else if(first==1) -Numfirstdigit=atoi (strn+1)+1;//Convert a string to an integer - - intnumotherdigits=first* (length-1) *powerbase10 (length-2); - intNUMRECURSIVE=NUMBEROF1 (strn+1); in - returnnumfirstdigit+numotherdigits+numrecursive; to } + - intPowerBase10 (unsignedintN) the { * intresult=1; $ for(unsignedintI=0; i<n;++i)Panax NotoginsengResult *=Ten; - returnresult; the } +
Number of occurrences from 1 to integer n in 1