Kodaks-iMac-2:Marco guwen$ vim numberOfOne.c
/*
编程之美 1的数目
2013.5.15 marco yao
*/
#include <stdio.h>
int sum(int n)
{ /*十进制*/
int count = 0, factor = 1;
int low,high, bitnum;
while(n/factor != 0)
{
high = n/(factor*10);
low = n - (n/factor)*factor;
bitnum = (n/factor)%10;
switch(bitnum)
{
case 0:
count += high*factor;
break;
case 1:
count += high*factor + low+1;
break;
default:
count += (high+1)*factor;
break;
}
factor *= 10;
}
return count;
}
int sum_2(int n)
{ /*二进制*/
int count = 0;
int low, high,bitnum=0,factor=1;
while(n/factor != 0)
{
low = n - (n/factor)*factor;
high = n/(factor*2);
bitnum = n/factor%2;
if(!bitnum)
count += high*factor;
else
count += high*factor + low +1;
factor *=2;
}
return count;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
printf("the num of \"1\" is %d\n",sum_2(n));
}
return 0;
}
<编程之美> 1的数目 c代码实现
最新推荐文章于 2023-11-26 11:28:41 发布