tutorialcup
Hamming Distance Leetcode Solution
Problem Statement
In this problem, we are given two integers, A and B, and the goal is to find the hamming distance between the given integers. The integers are greater that/equal to 0 and less than 231
Example
First Integer = 5 , Second Integer = 2
3
First Integer = 4 , Second Integer = 5
1
Approach(Counting Bit by Bit)
The first thing which is very clear is that since we need to find the number of bits where the corresponding bit values in the given two numbers are different, we need to do bitwise-XOR of the given integers. The results that XOR will produce in an individual bit position would be '1' if the bits in the two integers at that position were different. Otherwise, the XOR will produce a '0' at that position.
Now that we have deduced this part, the only follow-up remaining is to efficiently find out the numbers of bits which are set (bit value = '1') in the bitwise XOR of the given integers. In order to count this value, we loop for every bit (from 0 to 30) and check whether is set in the XOR value or not.
Algorithm
- Store the bitwise XOR of the two integers in a variable - xor_
- Initialize cnt = 0 to store the result
- For every i = 0 and i < 31:
- If the 'ith' bit is set in xor_
- Increment cnt: cnt++
- Increment i
- Return cnt
Implementation of Hamming Distance Leetcode Solution
C++ Program
#include
usin
www.tutorialcup.com/leetcode-solutions/hamming-distance-l...
Hamming Distance Leetcode Solution
Problem Statement
In this problem, we are given two integers, A and B, and the goal is to find the hamming distance between the given integers. The integers are greater that/equal to 0 and less than 231
Example
First Integer = 5 , Second Integer = 2
3
First Integer = 4 , Second Integer = 5
1
Approach(Counting Bit by Bit)
The first thing which is very clear is that since we need to find the number of bits where the corresponding bit values in the given two numbers are different, we need to do bitwise-XOR of the given integers. The results that XOR will produce in an individual bit position would be '1' if the bits in the two integers at that position were different. Otherwise, the XOR will produce a '0' at that position.
Now that we have deduced this part, the only follow-up remaining is to efficiently find out the numbers of bits which are set (bit value = '1') in the bitwise XOR of the given integers. In order to count this value, we loop for every bit (from 0 to 30) and check whether is set in the XOR value or not.
Algorithm
- Store the bitwise XOR of the two integers in a variable - xor_
- Initialize cnt = 0 to store the result
- For every i = 0 and i < 31:
- If the 'ith' bit is set in xor_
- Increment cnt: cnt++
- Increment i
- Return cnt
Implementation of Hamming Distance Leetcode Solution
C++ Program
#include
usin
www.tutorialcup.com/leetcode-solutions/hamming-distance-l...