题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。
#include <iostream>
using namespace std;
class CountOne
{
private:
int num;
int len;
public:
CountOne(int num):num(num)
{
len = 0;
int n = num;
while(n)
{
len++;
n/=10;
}
}
int countOneBy(int number,int index)
{
int n1,n2;
n1 = num/pow(index);
n2 = num%pow(index-1);
if(0==number)
{
return n1*pow(index);
}
else
{
if(1==number)
{
return n1*pow(index-1)+n2+1;
}
else
{
return (n1+1)*pow(index-1);
}
}
}
int sumOne()
{
int sum = 0;
for(int i = 1;i<=len;i++)
{
sum+=countOneBy(findIndex(i),i);
cout<<i<<" "<<sum<<" "<<countOneBy(findIndex(i),i)<<" "<<len<<endl;
}
return sum;
}
int pow(int i)
{
int n = 1;
for(int j = 0;j<i;j++)
n*=10;
return n;
}
int findIndex(int index)
{
int n = num;
int n1 = n/pow(index);
int n2 = n/pow(index-1);
return n2-10*n1;
}
};
int main()
{
CountOne co(11);
int sum = co.sumOne();
cout<<sum<<endl;
return 0;
}