Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc).
Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits.
Above is simple Half Adder logic 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.
Following is the recursive implementation for the same approach.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Subtract two numbers without using arithmetic operators
- Bitwise Operators in C/C++
- How to swap two numbers without using a temporary variable?
- Find the element that appears once
- Detect if two integers have opposite signs
- To find sum of two numbers without using any operator
- Count total set bits in all numbers from 1 to n
- Swap bits in a given number
- Binomial Coefficient | DP-9
- Smallest of three integers without comparison operators
- A Boolean Array Puzzle
- Program to count number of set bits in an (big) array
- Add 1 to a given number
- Find the two non-repeating elements in an array of repeating elements
- Count number of bits to be flipped to convert A to B
Improved By : vt_m