Solution by sharmish

  • 0

    Approach #1

    Since we need to identify the number of positions at which the corresponding bits are different, the first thought would be to XOR both the numbers.
    XOR of two bits is 1 only if both the numbers are different.
    0^1 = 1
    1^0 = 1
    0^0 = 0
    1^1 = 0

    Return the count of set bits in XOR of two given numbers


    public class Solution {
      public int hammingDistance(int x, int y) {
          return Integer.bitCount(x^y);

    Complexity Analysis

    • Time complexity : The run time depends on the number of bits in $$n$$ where $$n$$ is the binary representation of $$x$$ or $$y$$. Because $$n$$ in this piece of code is a 32-bit integer, the time complexity is $$O(1)$$

    • Space complexity : The space complexity is $$O(1)$$, since no additional space is allocated

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.