Explanation

Above is simple Half Adder Half Adderlogic that can be used to add 2 single bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result

Intuition

  • Should theset_bits be present at different location in both number forbitwise_XOR to work?
  • Yes for above for set bitsbitwise_AND is used, which gives the carry bits. This reminds me of carry digit that was taught to us in first or second standard.
  • What do << operator do?

Code

Javascript

// Define a function that adds two numbers using bitwise operations
function addUsingBitwise(num1, num2) {
    // Iterate until there is no carry left
    while (num2 !== 0) {
        // Calculate the common set bits of num1 and num2 and assign it to carry
        let carry = num1 & num2;
 
        // XOR of num1 and num2 gives the sum of bits without considering the carry
        num1 = num1 ^ num2;
 
        // Shift the carry to the left to be added in the next iteration
        num2 = carry << 1;
    }
    // Return the final result
    return num1;
}
 
// Example usage
const result = addUsingBitwise(5, 7);
console.log(result); // Output: 12
 
#### [[Python]]
```python
# Python3 Program to add two numbers
# without using arithmetic operator
def Add(x, y):
 
    # Iterate till there is no carry
    while (y != 0):
     
        # carry now contains common
        # set bits of x and y
        carry = x & y
 
        # Sum of bits of x and y where at
        # least one of the bits is not set
        x = x ^ y
 
        # Carry is shifted by one so that  
        # adding it to x gives the required sum
        y = carry << 1
     
    return x
 
print(Add(15, 32))