从1到N的整数中1出现的次数
/* * 1-n整数中1出现的次数.cpp * * Created on: 2018年5月1日 * Author: soyo */ #include<iostream> using namespace std; int NumberOf1( unsigned int n) { int number=0; while(n>=1) { if(n%10==1) number++; n=n/10; } return number; } int NumberOf1Between1AndN(unsigned int n) { unsigned int i; int number=0; for(i=0;i<=n;i++) { //cout<<i<<" "; number+=NumberOf1(i); } return number; } int main() { unsigned int n; cin>>n; int num; num=NumberOf1Between1AndN(n); cout<<endl; cout<<"Num中1的个数为:"<<num<<endl; }
结果:
100 Num中1的个数为:21