Check if it is possible to make given two numbers equal or not by changing 1 bit or 2 bits once
Given two positive integers A and B, perform one of the following operations only once to make the numbers equal.
- Change the ith bit of a number to 0 or 1
- Change the ith bit to 0 or 1 in A and jth bit to 0 or 1 in B
If it’s possible to make the numbers equal, then print “Yes”. Otherwise, print “No”.
Examples:
Input: A = 5, B = 15
Output: Yes
Explanation: The binary representations of the numbers 5 and 15 are 0101 and 1111 respectively.
Now, change the fourth bit of the number 5 to 1 and the second bit of the number 15 to 0.
Therefore, both the numbers become equal, i.e. 13.Input: A = 8, B = 7
Output: No
Approach: The given problem can be solved by counting the difference of set bits in both numbers i.e. in how many positions the bits of both the numbers are different from each other. If the count is more than two then it is not possible to make the numbers equal.
Below is the implementation of the above approach:
C++
// C++ program to check if it// is possible to make the two// numbers equal or not#include <bits/stdc++.h>using namespace std; // Function to count the different bits// in both numbersvoid makeNumbersEqual(int A, int B){ // Stores the number of different bits int diff = 0; // Stores the binry representations of // a and b respectively bitset<32> ar(A), br(B); for (int i = 0; i < 32; i++) { if (ar[i] != br[i]) diff++; } if (diff <= 2) cout << "Yes"; else cout << "No";} // Driver Codeint main(){ int A = 5, B = 15; makeNumbersEqual(A, B); return 0;} |
Yes
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.

