蓝桥杯编程每日一题——02 移位和与运算的应用

DAY 02 移位和与运算的应用

题目:设计一个函数,输入一个整数,输出该二进制表示中1的个数。

METHOD 1:左移位

1<<0                      1<<1               1<<2             1<<3

   1001                   1001                1001            1001

&      1                        1                    1                1

————               ————         ————      ————

   0001                   0000                 0000            1000

import java.util.Scanner;

public class Day02 {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int N=sc.nextInt();
        System.out.println(Integer.toString(N,2));
        int count=0;
        for (int i = 0; i <32 ; i++) {
            if ((N&(1<<i))==(1<<i)){
                count++;
            }
        }
        System.out.println(count);
    }
}

METHOD 2:右移位

  N>>0                N>>1               N>>2              N>>3

  1001                  100                  10                        1

&      1                      1                    1                        1

————            ————        ———           ————       

  0001                  000                   00                        1

import java.util.Scanner;

public class Day02 {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int N=sc.nextInt();
        System.out.println(Integer.toString(N,2));
        int count=0;
        
        for (int i = 0; i < 32; i++) {
            if (((N>>i)&1)==1){
                count++;
            }
            
        }
        System.out.println(count);
    }
}

METHOD 3:巧用减一

巧计:一个二进制数减一后,其从低位依次数的第一个1变为0,比其低的位数均为0!!!!

  1001000                          1000000

-             1                                      1

——————                  ——————

  1000111                          01111111

&1001000                         10000000

——————                  ———————

  1000000                        000000000

import java.util.Scanner;

public class Day02 {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int N=sc.nextInt();
        System.out.println(Integer.toString(N,2));
        int count=0;
        while(N!=0){
            N=((N-1)&N);
            count++;
        }
        System.out.println(count);
    }
}

 

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值