题目:给一个斐波那契数列0,1,1,2,3,5,8,13,21,34…然后给一个整数n,求数列中前n个数含有多少个1.
这题太简单了。
招银网络的测试岗位竟然还考数据库大题,措手不及,忘记复习了。。。
#include <iostream>
#include <vector>
using namespace std;
int num_of_1(int n)
{
int count = 0;
while (n)
{
if (n % 10 == 1)
count++;
n /= 10;
}
return count;
}
//0,1,1,2,3,5,8,13,21,34...
int main()
{
int n;
while (cin >> n)
{
if (n == 1)
{
cout << 0 << endl;
}
else if (n == 2)
{
cout << 1 << endl;
}
else
{
vector<int>f(n + 1, 0);
f[1] = 0;
f[2] = 1;
for (int i = 3; i <= n; i++)
{
f[i] = f[i - 1] + f[i - 2];
}
int res = 0;
for (int i = 1; i <= n; i++)
{
res += num_of_1(f[i]);
}
cout << res << endl;
}
}
system("pause");
return 0;
}