Monday, November 29, 2021
HomeTop Coding QuestionC++ program to add two numbers without using plus operator.

C++ program to add two numbers without using plus operator.

Given a number we have to add two numbers without using plus operator and store their resultant result into a variable.

Addition of number is same as we do add numbers in math by using + operator.

Approach:Without + operator

Example:

input:3 ,4
output: 7

input:9,10
output: 19

Logic:

we will add two number by using xor operator by taking care of carry bit.
#include<bits/stdc++.h>
using namespace std;
int main() {
   int num1,num2;
   cout<<"enter two number"<<endl;
   cin>>num1>>num2;
   //we will using xor operator to add two number.
   
while(num2!=0)
{
    int carry=num1&num2;//calculating carry value between two number.
     num1=num1^num2;
    num2=carry<<1;//shifting carry by 1
    
}
cout<<num1<<endl;
    
}

Output:

enter two number: 4 5
result:9

Time Complexity:O(1)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments