Bit manipulation

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

--

--

--

Data Scientist/MLE/SWE @takemobi

Love podcasts or audiobooks? Learn on the go with our new app.

Thick Client Penetration testing — TCP traffic interception using mitm_relay and Burp.

Visualising the Cloud— Diagrams-as-code?

Modelling Bounded Contexts with the Bounded Context Canvas: A Workshop Recipe

Using Ransack with Ajax data tables in ruby on rails

Jotai

Implement an orchestration automation solution

How to Deploy Logstash to a Kubernetes cluster

Understanding Design Patterns: Iterator using Dev.to and Medium social networks!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jimmy Shen

Jimmy Shen

Data Scientist/MLE/SWE @takemobi

More from Medium

Search in a Binary Search Tree

FINDING ARTICULATION POINT IN A GRAPH

Finding the Articulation Points OR Cut Vertices in a Graph