判断二进制1的个数三种方法

复制代码
 //判断二进制1的个数;
    public static void main4(String[] args) {
        int a = -1;
        int count = 0;
        for (int i = 0; i < 32; i++) {
            if(((a>>i)&1) != 0){
               count++;
            }
        }
        System.out.println(count);
    }

通过循环32次移位实现

2.每次移位后判断后面是否还有1

复制代码
public static void main2(String[] args) {
        int a = -1;
        int count = 0;
        while(a != 0){
            if((a & 1) == 1){
                count++;
            }
            a = a>>>1;
        }
        System.out.println(count);
    }

3.通过与 比自己小1的数 进行与运算 来消除 该数字里面的 1

复制代码
 public static void main3(String[] args) {
        int a = -1;
        int conut = 0;
        while(a != 0){
            a = a&(a-1);
            conut++;
        }
        System.out.println(conut);
    }
相关推荐
小马爱打代码13 分钟前
Spring Boot:模块化实战 - 保持清晰架构
java·spring boot·架构
Zsy_05100323 分钟前
【数据结构】二叉树OJ
数据结构
小坏讲微服务43 分钟前
SpringBoot4.0整合knife4j 在线文档完整使用
java·spring cloud·在线文档·knife4j·文档·接口文档·swagger-ui
8***Z891 小时前
springboot 异步操作
java·spring boot·mybatis
i***13241 小时前
Spring BOOT 启动参数
java·spring boot·后端
坚持不懈的大白1 小时前
后端:SpringMVC
java
IT_Octopus1 小时前
(旧)Spring Securit 实现JWT token认证(多平台登录&部分鉴权)
java·后端·spring
kk哥88991 小时前
Spring详解
java·后端·spring
S***26751 小时前
Spring Cloud Gateway 整合Spring Security
java·后端·spring
Tao____1 小时前
开源物联网平台
java·物联网·mqtt·开源·设备对接