1的数目
题目:写一个函数f(N),返回1到N之间出现的"1"的个数。
(1)循环遍历1-N,分别求每个数字的中包含1的个数。
#include <iostream>
using namespace std;
int Count(long num)
{
int temp=0;
while (num)
{
temp+=num % 10 == 1 ? 1 : 0;
num/=10;
}
return temp;
}
int main()
{
long num=100000000;
long i;
int total=0;
for (i=1; i<=num; ++i)
{
total+=Count(i);
}
cout<<"total="<<total<<endl;
}
(2)假设N=A*10^i + B*10^(i-1) + C,即A,B和C分别代表第i位的高位数值,当前位数值和低位数值。第i位上1的个数与A,B,C可能都有关。
当B > 1时,([0-A],1,*)<(A,B,C),一共是(A+1)*10^i个1,高位相关。
当B = 1时,([0-(A-1),1,*])<(A,B,C),[A,1,[0-C]] <= (A,B,C),一共是A*10^i+C+1个1,高位低位相关。
当B = 0时,([0-(A-1)],1,*)<(A,B,C),一共是A*10^i个1,高位相关。
#include <iostream>
using namespace std;
int find_num(int N, int x)
{
int count = 0;
int A,B,C,factor;
factor = 1;
while(N >= factor)
{
A = N / (factor * 10);
B = N / factor % 10;
C = N % factor;
cout << "(A,B,C): " << "(" << A << "," << B << "," << C << ")" << endl;
if(B > x)
count += (A+1) * factor;
else if(B == x)
count += A * factor + C + 1;
else
count += A * factor;
factor *= 10;
}
return count;
}
int main()
{
int N;
while(true)
{
cout << "输入N:";
cin >> N;
int count = find_num(N, 1);
cout << 1 << "到" << N << "中1的个数:";
cout << count << endl;
cout << endl;
}
return 0;
}

浙公网安备 33010602011771号