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();
//        }
//
//    }
}
相关推荐
Code季风3 分钟前
深度优化 spring 性能:从缓存、延迟加载到并发控制的实战指南
java·spring boot·后端·spring·缓存·性能优化
风象南11 分钟前
SpringBoot自定义RestTemplate的拦截器链
java·spring boot·后端
Victor3561 小时前
MySQL(138)如何设置数据归档策略?
后端
Victor3561 小时前
MySQL(137)如何进行数据库审计?
后端
FreeBuf_9 小时前
黄金旋律IAB组织利用暴露的ASP.NET机器密钥实施未授权访问
网络·后端·asp.net
张小洛10 小时前
Spring AOP 是如何生效的(入口源码级解析)?
java·后端·spring
why技术11 小时前
也是出息了,业务代码里面也用上算法了。
java·后端·算法
白仑色13 小时前
完整 Spring Boot + Vue 登录系统
vue.js·spring boot·后端
ZhangApple14 小时前
微信自动化工具:让自己的微信变成智能机器人!
前端·后端
Codebee14 小时前
OneCode 3.0: 注解驱动的Spring生态增强方案
后端·设计模式·架构