二进制序列

目录

找出二进制序列中数字1的个数

输出二进制序列中偶数位与奇数位


题一:找出二进制序列中数字1的个数

方法一:目标数字向右移,一直移到最高位

public class Test {
    public static void main1(String[] args) {
        int num = 7;
        int count = 0;
        int n = 0;
        while(n < 32){
            if(((num >> n) & 1) == 1){
                count++;
            }
            n++;
        }
        System.out.println(count);
    }
}

方法二:目标数字向右移,一直移到无效位

解法与方法一一致,但方法一对于任何数都要右移32位,效率较低,方法二可以只计算有效位。

public class Test {
    public static void main2(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt()){
            int num = sc.nextInt();
            int count = 0;
            while(num != 0){
                if((num & 1) != 0){
                    count++;
                }
                num = num >> 1;
            }
            System.out.println(count);
        }
        sc.close();
    }
}

方法三:相邻数字按位与,一直算到为 0 止

一直和相邻的数字运算,最终会得到0,算了几次就有几个1。

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while(sc.hasNextInt()){
            int num = sc.nextInt();
            int count = 0;
            while(num != 0){
                num = num & (num - 1);
                    count++;
            }
            System.out.println(count);
        }
        sc.close();
    }
}


题二:输出二进制序列中偶数位与奇数位

public class Test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n =0;
        while(sc.hasNextInt()){
            int num = sc.nextInt();
            //偶数位
            System.out.print("偶数位:");
            for (n = 30; n >= 0; n -= 2) {
                System.out.print((num >> n) & 1);
            }
            System.out.println();
            //奇数位
            System.out.print("奇数位:");
            for (n = 31; n >= 1 ; n-= 2) {
                System.out.print((num >> n) & 1);
            }
            System.out.println();
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@糊糊涂涂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值