Check if it is possible to make given two numbers equal or not by changing 1 bit or 2 bits once in C++


In the realm of computer programming, many operations center around numerical values. In certain cases, one may need to determine if modifying a few bits could bring two numbers together as equals. While this predicament may pose challenges, the right strategy leads to successful solutions.

Syntax

To establish a solid foundation for comprehending the algorithm, let us first become acquainted with the syntax used in subsequent coding by employing this specific method −

bool checkEquality(int num1, int num2);

To determine if two given integers, namely num1 and num2, can be made equal by altering one or two bits exclusively, the checkEquality function is utilized to generate a boolean response.

Algorithm

Here is a step-by-step breakdown of our algorithm −

  • Determine the exclusive OR of num1 and num2, assigning the output to a new variable xorResult.

  • Utilize the algorithm to compute the amount of set bits in xorResult, and subsequently assign the result to a variable denominated as setBitCount.

  • For a successful outcome in the operation, setBitCount must not exceed 2. Under this circumstance, our function would deliver a true result. Should it outnumber this specified threshold, we can conclude that our output must be false.

  • Now that we possess the algorithm, let us delve into a minimum of two distinct methods for addressing this issue.

Approach 1: Bit Manipulation

In this approach, we will use bit manipulation to check if it is possible to make the numbers equal.

Example

#include <iostream>

bool checkEquality(int num1, int num2) {
   int xorResult = num1 ^ num2;
   int bitCheck = xorResult & (xorResult - 1);
   return (bitCheck == 0);
}

int main() {
   int number1, number2;
   std::cout << "Enter the first number: ";
   std::cin >> number1;
   std::cout << "Enter the second number: ";
   std::cin >> number2;
    
   bool result = checkEquality(number1, number2);
   if (result) {
      std::cout << "It is possible to make the numbers equal by changing only one or two bits." << std::endl;
   } else {
      std::cout << "It is not possible to make the numbers equal by changing only one or two bits." << std::endl;
   }  
   return 0;
}

Output

Enter the first number: Enter the second number: It is not possible to make the numbers equal by changing only one or two bits.

Explanation

C++ code presented conducts a straightforward check whether it's practical to establish perfect alignment between two provided numerical values when modifying either one or two bits contained within them alone are changed during process execution. To achieve this objective , an integral component of this code includes defining a special function known as "checkEquality." Using this custom function requires that we supply exactly two integer variables as inputs.The output type for this particular function has been designed using Boolean logic so users can easily obtain results indicating whether changes were enough for perfect numeric alignment of arguments supplied into said function during runtime.

For computing purposes,this program employs XOR algorithm proceeds by comparing aforementioned integer inputs via checkEqualitymethod.Afterwards auto-storing outcome gets caught within variable “xorResult.” A critical determinant for next steps involves calculating bitwise ANDintermediate results between xorResult and XORResult - 1. It is at this stage where bitCheck variable assumption becomes necessary when a value of "0" is returned. Since it signifies fulfillment of necessary conditions, we can assume that either one or two bits present in integer inputs require variation to satisfy the request imposed by the checkEquality function. Upon completion, the program prompts users for input supply before feeding arguments into checkEquality method as final computation stage.After the process concludes, output messages indicating presence/absence of required bit level alterations become visible with the appropriate message displayed on console output.This implementation showcases an excellent example involving bitwise operations and XOR utilization pathways from within C++.

Approach 2: Hamming Distance Approach

In this approach, we will use the concept of Hamming distance to solve the problem.

Example

#include <iostream>

int countSetBits(int num) {
   int count = 0;
   while (num) {
      num &= (num - 1);
      count++;
   }
   return count;
}

bool checkEquality(int num1, int num2) {
   int xorResult = num1 ^ num2;
   int setBitCount = countSetBits(xorResult);
   return (setBitCount <= 2);
}

int main() {
   int number1, number2;
   std::cout << "Enter the first number: ";
   std::cin >> number1;
   std::cout << "Enter the second number: ";
   std::cin >> number2;
    
   bool result = checkEquality(number1, number2);
   if (result) {
      std::cout << "It is possible to make the numbers equal by changing only one or two bits." << std::endl;
   } else {
      std::cout << "It is not possible to make the numbers equal by changing only one or two bits." << std::endl;
   }   
   return 0;
}

Output

Enter the first number: Enter the second number: It is not possible to make the numbers equal by changing only one or two bits.

Explanation

In this instance, we present a C++ program which aims to establish if we can effect change on just one or possibly both bit(s) in order to make two separate numbers equivalent. Additionally, there exists a function called "countSetBits," which leverages Kemighan's Algorithm towards determining how many set bits exist within an integer value.

In the checkEquality function, the code calculates the XOR (exclusive OR) of the two input numbers and stores it in xorResult. The former statement triggers the countSetBits function in order to ascertain the quantity of bits set within xorResult which is then amassed in setBitCount. Whenever setBitCount is identified as being either two or fewer, it follows that simply one or two bits require modification for equalization, resulting in a true return from the function. Otherwise, a false return is executed

In the main function, the program prompts the user to enter two numbers. It then calls the checkEquality function with the user-provided numbers and stores the result. Finally, based on the value of the result, the program prints an appropriate message indicating whether it is possible or not to make the numbers equal by changing only one or two bits.

This code provides a clear implementation of the problem, utilizing the XOR operation and Kernighan's algorithm to count set bits efficiently.

Conclusion

Our article delves into the problem of determining if two given numbers can be made equal while changing only one or two bits. To solve this problem, we proposed two effective approaches - the bit manipulation approach and Hamming distance approach. Both approaches provide efficient solutions to the problem. We also provided real, fully executable code examples based on these approaches. By understanding and implementing these approaches, you can effectively check if it is possible to make two numbers equal by altering a few bits.

Updated on: 25-Jul-2023

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements