[01 Aug 2020] Add two numbers without using arithmetic operators

 Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc).

// C++ Program to add two numbers 
// without using arithmetic operator 
#include <bits/stdc++.h>
using namespace std;
  
int Add(int x, int y) 
    // Iterate till there is no carry 
    while (y != 0) 
    
        // carry now contains common 
        //set bits of x and y 
        int 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; 
  
// Driver code
int main() 
    cout << Add(15, 32); 
    return 0; 
  

Following is the recursive implementation for the same approach.

int Add(int x, int y)
{
    if (y == 0)
        return x;
    else
        return Add( x ^ y, (x & y) << 1);

}

Output :

47

Comments

Popular posts from this blog

Kth most frequent Character in a given String

[16 Feb 2020] Given an array where every element occurs three times, except one element which occurs only once.

[17 Feb 2020] Given an array of integers, find the nearest smaller number for every element such that the smaller element is on left side.