https://leetcode.com/problems/number-complement/
class Solution {
public int findComplement(int num) {
int i = Integer.numberOfLeadingZeros(num);
return ~num << i >> i;
}
}
也可以参考评论区的答案:
Idea:
num
num = 5
num binary = 0...0101
~num binary = 1...1010
* Now we've flipped all the bits but it also flipped previously insignificant bits (0s),
so to revert them back to 0s, we need to only keep the significant bits and turn off the insignificant bits.
* This can be done by using mask of 1s having size equal to number of bits in num. This mask is (1 << nBits) - 1.
* This is a standard mask in bit manipulation problems..
~num binary & mask = (1...1010) & (0...0111) = 0...0010 [Ans]
T/S: O(1)/O(1)
public int findComplement(int num) {
var nBits = (int) Math.floor((Math.log(num) / Math.log(2)) + 1);
var mask = (1 << nBits) - 1;
return ~num & mask;
}
1 liner variation of above method
public int findComplement(int num) {
return ~num & (Integer.highestOneBit(num) - 1);
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/sinat_42483341/article/details/122169040
内容来源于网络,如有侵权,请联系作者删除!