牛客刷题之二进制中1的个数

本文介绍了一种计算整数二进制表示中1的个数的方法,涵盖了正数和负数的处理,对于负数采用补码表示并进行相应的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

解题思路:

       按照常规想法,如果是正数,则直接转换为二进制求1的个数即可。

                                 如果是负数,先转换为正数,然后取反加1。

public class Solution {
    public int NumberOf1(int n) {
        if(n>=0){
            int count = 0;
            while(n != 0){
                if(n % 2 == 1){
                    count += 1;
                }
                n = n / 2;
            }
            return count;
        }else{
            n = 0-n;
            int[] array = new int[32];
            //将数组初始化为0
            for(int i =0;i<32;i++){
                array[i] = 0;
            }
            //求其二进制表示
            for(int i=0;n!=0;i++){
                if(n %2 == 1){
                   array[i] = 1;
                }else{
                   array[i] = 0;
                }
                n = n /2;
            }
            //每位都进行取反,注意,包括符号位
            for(int i =0;i<32;i++){
                if(array[i] == 0){
                    array[i] = 1;
                }else{
                    array[i] = 0;
                }
                
            }
            //末尾加1
            if(array[0]== 0){
                array[0] = 1;
            }else{
                int i = 0;
                while(array[i] != 0 && i<31){
                    array[i] = 0;
                    i += 1;
                }
                array[i] = 1;
            }
            //统计1的个数
            int count1 = 0;
            for(int i =0;i<32;i++){
                if(array[i] == 1){
                    count1 += 1;
                }
            }
            return count1 ;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值