Count Differing Positions in Two Binary Integers

Quick Overview

Count the binary positions at which two nonnegative integers differ. Preserve zero inputs, the nonnegative 31-bit range and the original Hamming-distance callable interface.

Count Differing Positions in Two Binary Integers

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

# Count Differing Positions in Two Binary Integers Given nonnegative integers `x` and `y`, return the number of binary bit positions where their bits differ. Leading zero bits are included when aligning the representations and do not change the count. This count is their Hamming distance. ### Interface `class Solution { public: int hammingDistance(int x, int y); };` ### Example 1 ```text Input: x = 10, y = 5 Output: 4 ``` The aligned representations are `1010` and `0101`; all four positions differ. ### Example 2 ```text Input: x = 0, y = 8 Output: 1 ``` The representations `0000` and `1000` differ at one position. ### Constraints - `0 <= x, y <= 2147483647` (`2^31 - 1`). ### What a Strong Answer Covers - Counting positions rather than the arithmetic difference of the values. - Zero inputs, equal values and the highest permitted bit. - Safe bit operations for the full nonnegative input domain. ```hint Compare aligned positions Consider one corresponding binary position at a time. What should it contribute when the bits agree or disagree? ```

Overview: Count the binary positions at which two nonnegative integers differ. Preserve zero inputs, the nonnegative 31-bit range and the original Hamming-distance callable interface.

Google logo
Google
easySoftware EngineerOtherCoding & Algorithms
0
0

Count Differing Positions in Two Binary Integers

Given nonnegative integers x and y, return the number of binary bit positions where their bits differ. Leading zero bits are included when aligning the representations and do not change the count. This count is their Hamming distance.

Interface

class Solution { public: int hammingDistance(int x, int y); };

Example 1

Input: x = 10, y = 5
Output: 4

The aligned representations are 1010 and 0101; all four positions differ.

Example 2

Input: x = 0, y = 8
Output: 1

The representations 0000 and 1000 differ at one position.

Constraints

  • 0 <= x, y <= 2147483647 ( 2^31 - 1 ).

What a Strong Answer Covers Guidance

  • Counting positions rather than the arithmetic difference of the values.
  • Zero inputs, equal values and the highest permitted bit.
  • Safe bit operations for the full nonnegative input domain.