#include "stdio.h"
#include "stdlib.h"
int count1(int n);
int count2(int n);
int main(void)
{
int x;
printf("输入一个数:");
scanf("%d",&x);
printf("\n从0到%d一共遇到%d(%d)个1\n",x,count1(x),count2(x));
return 0;
}
//解法一
int count1(int n)
{
int count = 0;
int i,t;
//遍历1到n
for(i=1;i<=n;i++)
{
t=i;
//依次处理当前遍历到的数字的各个位
while(t != 0)
{
//若为1则统计加一
count += (t == 1)?1:0;
t/=10;
}
}
return count;
}
//解法二:
int count2(int n)
{
int count = 0;//统计变量
int factor = 1;//分解因子
int lower = 0;//当前处理位的所有低位
int higher = 0;//当前处理位的所有高位
int curr =0;//当前处理位
while(n/factor != 0)
{
lower = n - n/factor*factor;//求得低位
curr = (n/factor);//求当前位
higher = n/(factor*10);//求高位
switch(curr)
{
case 0:
count += higher * factor;
break;
case 1:
count += higher * factor + lower + 1;
break;
default:
count += (higher+1)*factor;
}
factor *= 10;
}
return count;
}
#include "stdio.h"
#include "stdlib.h"
int count1(int x);
int count2(int x);
int count3(int x);
int main(void)
{
int x;
printf("输入一个数:\n");
setbuf(stdin,NULL);
scanf("%d",&x);
printf("%d转二进制中1的个数是:",x);
printf("\n解法一:%d",count1(x));
printf("\n解法二:%d",count2(x));
printf("\n解法三:%d",count3(x));
printf("\n");
return 0;
}
//除二、余二依次统计每位
int count1(int x)
{
int c=0;
while(x)
{
if(x%2==1)
c++;
x/=2;
}
return c;
}
//向右移位,与1按位与统计每位
int count2(int x)
{
int c=0;
while(x)
{
c+=x & 0x1;
x>>=1;
}
return c;
}
//每次将最后一个1处理成0,统计处理次数
int count3(int x)
{
int c=0;
while(x)
{
x&=(x-1);
c++;
}
return c;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有