Bit manipulation

Jimmy (xiaoke) Shen
1 min readJun 23, 2020

137. Single Number II

An elegant solution from [1]

class Solution:
def singleNumber(self, nums: List[int]) -> int:
low_bits = high_bits = 0
for num in nums:
low_bits = ~high_bits & (low_bits ^ num)
high_bits = ~low_bits & (high_bits ^ num)
return low_bits

Another nice explanation about this nice solution in Chinese can be found in [2]

190. Reverse Bits

class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t ret = 0;
for(int i=0;i<32;++i)
{
ret = ret<<1;
if(n&(1<<i))
{
ret += 1;
}
}
return ret;
}
};

Reference

[1]https://medium.com/@lenchen/leetcode-137-single-number-ii-31af98b0f462

[2]https://blog.csdn.net/yutianzuijin/article/details/50597413?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-1

--

--