先来个例子:
n=3241
(1)千位中1的个数n/1000=3>1 1X1000个
(2)百位中1的个数n/100=32 32的个位是2>=1(3+1)X100=400个
(3)十位中1的个数n/10=324 324的个位是4>=1(32+1)X10=330个
(4)个位中1的个数n/1=3241 3241的个位是4>=1(324+1)X1=325个
共计1000+400+330+325=2055个
code
#include "stdafx.h" #include <iostream> #include <string> #include <stack> using namespace std; int mySum1s(int n) { int temp=n; int div=1; int cnt=0; while(temp!=0) { temp/=div; div*=10; } div/=10; int a,b; while(div!=0) { a=n/div; if(a>0 && a<10) { if(a==1) { cnt+=n-a*div+1; } else { cnt+=div; } } else { b=a%10; if(b>0) { cnt+=(a/10+1)*div; } else { cnt+=a/10*div; } } div/=10; } return cnt; } int main(int arc, char** argv) { int cnt=0; cnt=mySum1s(3241); cout<<cnt<<endl; system("pause"); return 0; }
(1)个位上的1:101/10=10101%10=1>010x1+(1-0)=11
(2)十位上的1:101/100=1101%100=1<101x10+0=10
(3)百位上的1:101/1000=0101%1000=101>990+(101-99)=2
code
#include "stdafx.h" #include <vector> #include <iostream> using namespace std; int numOfOnes(int num) { int n=0; int temp=num; while(temp!=0) { n++; temp/=10; } int div=1; int sum=0; while(n--) { div*=10; int a=num/div; int b=num%div; if(div/10-1<b && b<2*div/10) { sum+=a*div/10+(b-div/10+1); } else if(b>=2*div/10) { sum+=a*div/10+div/10; } else { sum+=a*div/10; } } return sum; } int main(void) { int n=112; int cnt=numOfOnes(n); cout<<"The number of one is "<<cnt<<"."<<endl; system("pause"); return 0; }