zoukankan      html  css  js  c++  java
  • How many '1's are there题解

    Description:

    Description:

    第一行输入数字n(n<=50),表示有n组测试用例,第2到第n+1行每行输入数m(m为整数),统计并输出m用二进制表示时,1的个数。

    例如:m=9时,二进制表示为1001,则输出2.

    Input:

    2

    3

    7

    Output:

    2

    3


    Hint:

    利用位运算


    一道比较简单的题目,其中也可以有高深的做法。虽然提示位运算,但因为不熟悉所以并没有用位运算。
     

    有错误的代码:(被电脑管家直接视为间谍软件给kill掉了。。)不太懂错的地方,先贴出来吧
    #include <stdio.h>
    int main() {
        int binary[20];
        int count = 0;
        int one = 0;  
        int n, i, num;
        scanf("%d", &n);
        for (i = 0; i < n; i++) {
            count = 0;
            one = 0;
            scanf("%d", &num);
            while (num != 0) {     
                binary[count] = num % 2;   
                num /= 2;
                count++;
            }
            for (i = count-1; i >= 0; i--) {   
                if (binary[i] == 1)
                one++;  
            }
            printf("%d
    ", one);
        }
    }

    最后通过的代码:

    #include <stdio.h>
    int main() {
        int binary[20];
        int n, i, num, j;
        scanf("%d", &n);
        for (i = 0; i < n; i++) {
            int count = 0;
            int one = 0;
            scanf("%d", &num);
            while (num != 0) {
                binary[count] = num % 2; 
                if (binary[count] == 1) {
                    one++;
                }
                num /= 2;
                count++;
            }
            printf("%d
    ", one);
        }
    }

    标答:

    #include<stdio.h>
     
    int bitcount(int x) {
            int count = 0;
            while (x != 0) {
                    x &= (x-1);
                    count++;
            }
            return count;
    }
     
    int main() {
            int num;
            int x;
            scanf("%d", &num);
     
            while (num--) {
                    scanf("%d", &x);
                    printf("%d
    ", bitcount(x));
            }
            return 0;
    }

    听说有一个函数

  • 相关阅读:
    iptables 常用命令解析
    iptables 常用处理动作
    centos7 中iptables、firewalld 和 netfilter 的关系
    iptables 的几个状态
    centos7 中没有service iptables save指令来保存防火墙规则
    iptables 数据走向流程
    数据库PDO简介
    php连接mySql,加密函数
    php数组,常量,遍历等
    php的会话控制
  • 原文地址:https://www.cnblogs.com/xieyuanzhen-Feather/p/5055517.html
Copyright © 2011-2022 走看看