您的位置:首页 > 编程语言

[编程之美2.4]1的数目

2013-04-10 21:52 435 查看
给定一个十进制正整数N,写下从1开始,到N的所有证书,然后数一下其中出现的所有的“1”的个数,例如

N = 2,写下1,2.这样出现了1一个“1”。

N = 12,我们会写下,1,2,3,4,5,6,7,8,9,10,11,12,这样1的个数是5.

题目1.写一个函数f(n),返回1到n之间出现的1的个数,比如f(12) = 5;

题目2.满足f(n)=n的最大的N是多少?

扩展问题:其他进制的表达方式也可以试试,例如二进制f(1) = 1, f(10) = 10,f(11) = 100,求f(n)

解答:最容易想到的方法就是从1开始遍历到n,将其中每个数中含有的1个数加起来,自然而然得到了从1到N所有的"1"的个数的和,此方法的复杂度为O(nlogn)。代码如下:

#include <iostream>
#include <stdlib.h>

using namespace std;

int countOne(int n)
{
int sum = 0;
while(n)
{
sum += (n % 10 == 1) ? 1 : 0;
n /= 10;
}
return sum;
}

int sum_of_one(int n)
{
int sum = 0;
for(int i = 1; i <= n; i++)
{
sum += countOne(i);
}
return sum;
}

int main()
{
int n;
cin >> n;
cout << sum_of_one(n) << endl;
system("pause");
}

解法二:
观察三个数:n = 123,113,103时1的个数,

n = 123时候,个位数上出现的1的个数为12+1,十位数上出现的1的个数为2*10,百位数上出现的1的个数为23+1,总共为57个

n = 113时候,个位数上出现的1的个数为11+1,十位数上出现的1的个数为10+3+1,百位数上出现的1的个数为13+1,总共为40个

n = 103时候,个位数上出现的1的个数为10+1,十位数上出现的1的个数为1*10,百位数上出现的1的个数为3 + 1,总数为25

由此可以推出:



代码如下:

#include <iostream>
#include <stdlib.h>

using namespace std;

int countOne_math_version(int n)
{
int iFactor = 1;

int high = 0;
int current = 0;
int low = 0;
int sum = 0;
while(n / iFactor)
{
low = n - (n / iFactor)*iFactor;
high = n / (iFactor * 10);
current = (n / iFactor) % 10;

switch(current)
{
case 0:
sum += high * iFactor;
break;
case 1:
sum += high * iFactor + low + 1;
break;
default:
sum += (high + 1) * iFactor;
break;
}
iFactor *= 10;
}

return sum;

}

int main()
{
int n;
cin >> n;
cout << countOne_math_version(n) << endl;
system("pause");
}
第二题和扩展提明天再想...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编程之美 算法