Top 100

Hamming Distance

Problem
LC 461
File
top100_LC461HammingDistance.java
Path
pkg5leetcode/top100/top100_LC461HammingDistance.java
Package
pkg5leetcode.top100
Command
java pkg5leetcode/top100/top100_LC461HammingDistance.java
Approach
XOR then count set bits in result.
Complexity
Time O(1), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/top100/top100_LC461HammingDistance.java
1package pkg5leetcode.top100;2 3/*4 * Hamming Distance | LC 4615 * APPROACH: XOR then count set bits in result.6 * COMPLEXITY: Time O(1), Space O(1)7 */8public class top100_LC461HammingDistance {9    static int hammingDistance(int x, int y) {10        int diff = x ^ y, count = 0;11        while (diff != 0) {12            count += diff & 1;13            diff >>>= 1;14        }15        return count;16    }17 18    public static void main(String[] args) {19        check(hammingDistance(1, 4) == 2, "case1");20        check(hammingDistance(3, 1) == 1, "case2");21        System.out.println("all tests passed");22    }23 24    static void check(boolean cond, String name) {25        if (!cond) throw new AssertionError("FAILED: " + name);26        System.out.println("  PASS " + name);27    }28}