Acwing801二进制中1的个数

题目

给定一个长度为 n 的数列,请你求出数列中每个数的二进制表示中 11 的个数。

输入格式:

第一行包含整数 n

第二行包含 n 个整数,表示整个数列。

输出格式:

共一行,包含 n 个整数,其中的第 i 个数表示数列中的第 i 个数的二进制表示中 1 的个数。

数据范围:

1≤n≤100000 0≤数列中元素的值≤10^9

输入样例:

复制代码
5
1 2 3 4 5

输出样例:

复制代码
1 1 2 1 2

代码

java 复制代码
package Acwing.basicAlgorithm;

import java.util.Scanner;

public class 二进制中1的个数_801 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
//        int[] a = new int[n];
        for (int i =0 ;i < n;i ++) {
            int x = in.nextInt();
            int count = 0;
            while (x != 0) {
                count ++;
                x -= bit(x);
            }
            System.out.print(count + " ");
        }


    }
    public static int bit(int x) {
        return x & -x;
    }
//java中把统计二进制个数方法封装在jdk中了,可以直接调用Integer类中的bitCount方法
//import java.io.BufferedInputStream;
//import java.util.Scanner;
//
//    public class Main {
//
//        public static void main(String[] args) {
//            Scanner scanner = new Scanner(new BufferedInputStream(System.in));
//            int n = scanner.nextInt();
//            for(int i=0;i<n;i++) {
//                System.out.print(Integer.bitCount(scanner.nextInt())+" ");
//            }
//            scanner.close();
//        }
//
//    }
}
相关推荐
Cosolar20 小时前
银河麒麟 / aarch64 系统:Docker + Docker Compose 完整安装教程
后端·程序员·架构
星释20 小时前
Rust 练习册 100:音乐音阶生成器
开发语言·后端·rust
kaliarch20 小时前
2025年IaC生态全景与实践指南:从工具选型到多云治理
后端·云计算·自动化运维
Coder-coco20 小时前
个人健康管理|基于springboot+vue+个人健康管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·mysql·论文
b***653220 小时前
springboot整合mybatis-plus(保姆教学) 及搭建项目
spring boot·后端·mybatis
5***E68520 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
x***010620 小时前
SpringSecurity+jwt实现权限认证功能
android·前端·后端
5***262220 小时前
Spring Boot问题总结
java·spring boot·后端
风生u21 小时前
go进阶语法
开发语言·后端·golang
xkroy21 小时前
Spring Boot日志
java·spring boot·后端