java 位运算_Kotlin/Java 位运算 All In One (附口诀)

9a6a7092daf8c78c0de70c97b0c0c106.png

不要忘记点赞哦

Kotlin source code

/** Shifts this value left by the [bitCount] number of bits. */public infix fun shl(bitCount: Int): Int/** Shifts this value right by the [bitCount] number of bits, filling the leftmost bits with copies of the sign bit. */public infix fun shr(bitCount: Int): Int/** Shifts this value right by the [bitCount] number of bits, filling the leftmost bits with zeros. */public infix fun ushr(bitCount: Int): Int/** Performs a bitwise AND operation between the two values. */public infix fun and(other: Int): Int/** Performs a bitwise OR operation between the two values. */public infix fun or(other: Int): Int/** Performs a bitwise XOR operation between the two values. */public infix fun xor(other: Int): Int/** Inverts the bits in this value. */public fun inv(): Int

LeetCode 476 Number Complement

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

用一个具体的例子讲一下这题的思路。比如说十进制的 5,用二进制表示是 0(28 个) + 0101
有效的二进制是 101 取其补码是 010,有效二进制 0(30 个) + 10 表示十进制二第一步计算出二进制的 5 前边有几个 0,用 Integer 类的 numberOfLeadingZeros方法,结果是 29 个第二步把二进制的按位做非运算得到 1(29 个) + 010第三步把它左移 29 位得到 010 + 0(29 个)第四部把它再右移 29 位得到 0(29 个) + 010 也是就十进制的 2
/*0000 ... 0101 ==> 5 (leadingZero = 32-3 = 29) inv1111 ... 1010*/fun findComplement(num: Int): Int {    val leadingZero = Integer.numberOfLeadingZeros(num)    return num.inv().shl(leadingZero).shr(leadingZero)}
/*0000 ... 0101 ==> 51111 ... 1111 ==> Int.MAX_VALUE1111 ... 1000 and0000 ... 01010000 ... 0000 ==> 01111 ... 1000 inv0000 ... 01110000 ... 0101 inv1111 ... 10100000 ... 0111 and1111 ... 1010==0000 ... 0010 ==> 2*/fun findComplement(num: Int): Int {    var flag = Int.MAX_VALUE    while (flag.and(num) != 0) {        flag = flag.shl(1)    }    return (flag.inv()).and(num.inv())}

欢迎大家关注我 [收藏] [点赞] [转发] ,谢谢,如果有问题可以评论或私信我哦。

Merci beaucoup !

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值