位运算的笔记-leetcode

这篇文章详细介绍了Java中位与运算的性质,包括如何使用x&(-x)获取最低位1,x&(x-1)清零最低位,以及2^n的左移操作(1<<n)。并通过LeetCode中的bitCount()函数实例展示了如何计数二进制表示中的1。
摘要由CSDN通过智能技术生成

位与运算的性质:

  1. x & (−x) 可以获得 x 的二进制表示中的最低位的 1 的位置;
    ( -x = x的反码+1)
  2. x & (x−1) 可以将 x 的二进制表示中的最低位的 1 置成 0。
  3. 2^(n) 用 java 写是 (1<<n): 相当于将1左移 n 位

LeetCode: 51
bitCount(): method of Integer class of java.lang package returns the count of the number of one-bits in the two’s complement binary representation of an int value.

// java bitCount():
import java.lang.Integer;
  
class Gfg {
    public static void main(String args[])
    {
        int a = 10;
        
        // Convert integer number to binary  format
        System.out.println(Integer.toBinaryString(a));
  
        // to print number of 1's in the number a
        System.out.println(Integer.bitCount(a));
    }
}

Output:

1010
2
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值