文章目录
Input
输入一个十进制数字
Output
输出该数字二进制 1 的个数
按总共32位进行计算
二、解题思路
没想法,这个解法完全没见过,就是前人总结的经验,正常人。。。我觉得正常人想不到。。。普通人写这个,一般需要循环多次,而这种算法,根本不需要循环那么多次,甚至把负数的情况都包含进去了,牛逼。。。如果我说的过分了,那么我就是沙雕。。。我承认。。。
#include<stdio.h>
int main() {
int n = 0;
scanf("%d", &n);
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
printf("%d",count);
return 0;
}
另一道题
链接: 题目详情
题目描述
求一个byte数字对应的二进制数字中1的最大连续数,例如3的二进制为00000011,最大连续2个1
本题含有多组样例输入。
输入描述:
输入一个byte数字
输出描述:
输出转成二进制之后连续1的个数
解题思路
上一道题的启发很大,这样只要考虑到算数右移和每移动一位正好就一定有0和1的位置重叠,那么只要与一下,就可以消去一个1,最后以最长的那串1消失,程序停止。
#include<stdio.h>
int main() {
int n = 0;
while (scanf("%d", &n) != -1) {
int count = 0;
while (n) {
count++;
n = n & (n << 1);
}
printf("%d", count);
}
return 0;
}
总结
猩猩的舅舅—狒狒