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
- Check if two numbers are equal without using arithmetic and comparison operators
- How to sum two integers without using arithmetic operators in C/C++?
- Subtract 1 without arithmetic operators
- Decimal to binary conversion without using arithmetic operators
- Check if n is divisible by power of 2 without using arithmetic operators
- Smallest perfect power of 2 greater than n (without using arithmetic operators)
- Check if two numbers are equal without using comparison operators
- Largest of two distinct numbers without using any conditional statements or operators
- Russian Peasant (Multiply two numbers using bitwise operators)
- Operators in C | Set 2 (Relational and Logical Operators)
- Arithmetic Mean
- Arithmetic Progression
- Arithmetic Number
- Sum of Arithmetic Geometric Sequence
Improved By : vt_m