Bit Manipulation · Easy

Check if Two Integers Differ by Exactly One Bit

Solve it on DeVert Campus - free code runner

Problem

Given two non-negative integers A and B, determine whether their binary representations differ in exactly one bit position (that is, whether the Hamming distance between A and B is exactly 1). Print "Yes" if so, otherwise print "No".

Input and output

Input: A single line containing two space-separated integers, A and B. Output: A single line containing "Yes" or "No".

Example

Input:
5 4
Output:
Yes

Constraints

0 <= A, B <= 2^31 - 1

Key observation

XOR is the single most useful bitwise operation for 'where do these two things differ' questions - it appears repeatedly across bit manipulation problems (finding a single non-repeated element, checking bit differences, and more) precisely because it isolates differences so directly.

Intuition

Check whether two numbers' binary representations differ in exactly one bit position. Brute force: Compare A and B bit by bit manually, counting how many positions differ - this works but is more manual bookkeeping than a single XOR-then-count operation. Optimised: XOR directly ISOLATES exactly the differing bit positions into a single result value, and counting its set bits (a well-known O(1)-ish operation, or O(number of bits) in the worst case) directly answers the question - no need to inspect each bit position of A and B separately and compare them one at a time.

Step by step

1. XOR the two numbers - the result has a 1 bit exactly where A and B differ, and 0 everywhere they agree. 2. Count the number of set bits in A XOR B. 3. The answer is Yes only when that count is EXACTLY 1.

Complexity

Time: O(1) - XOR is constant time, and counting bits in a fixed-width integer takes a small constant number of steps (or O(log(max value)) in the naive bit-by-bit counting approach). Space: O(1) - no extra storage.

Edge cases

A equal to B gives a Hamming distance of 0, so the answer is No; the maximum possible distance is 31 bits, which is also No.

Interview tip

Be ready to mention that this is exactly the 'Hamming distance equals 1' special case - recognizing the connection to the more general Hamming distance concept (used elsewhere, like 'Total Hamming Distance Across an Array') shows broader pattern awareness.

All DSA problems