Count Bits to Flip to Convert A to B
Interview Problems DSA practice problem on Onlearn.
Difficulty: medium.
Topics: Count number of bits to be flipped to convert A to B, Bitwise Operations, Time Complexity, Space Complexity, bit manipulation, binary representation.
Count Bits to Convert A to B Problem Statement Given two non negative integers, A and B, determine the number of bits that need to be flipped in the binary representation of A to convert it into the binary representation of B. Input Specification The input consists of two lines. The first line contains an integer A. The second line contains an integer B. Output Specification Output a single integer, the minimum number of bits to flip. Constraints 0 <= A, B <= 10^9 Sample Test Cases Sample Input 1 Sample Output 1 Explanation 1 Binary representation of 29 is ...011101. Binary representation of 15 is ...001111. To transform 29 into 15: The least significant bit (0th bit) changes from 1 to 1 (no flip). The 1st bit changes from 0 to 1 (flip). The 2nd bit changes from 1 to 1 (no flip). The 3rd bit changes from 1 to 0 (flip). Other higher bits are 0 and remain 0 (no flip). Thus, two bits need to be flipped.