Write a program to add two numbers without using the '+' operator.
Example 1:
Input:a=7,b=8
Output:a=15
Approach 1: Iterative
Java
public class TwoNumberSum {public static void main(String[] args) {int a = 7;int b = 8;int sum = addWithoutOperator(a, b);System.out.println(sum);}private static int addWithoutOperator(int a, int b) {while (b != 0) {int carry = a & b;a = a ^ b;//b=carry*2b = carry << 1;}return a;}}
C++
#include <bits/stdc++.h>using namespace std;//function which add two number//without using + operatorint addWithoutOperator(int a,int b){while(b!=0){int carry=a&b;a=a^b;//b=carry*2b=carry<<1;}return a;}int main(){int a=7,b=8;int sum=addWithoutOperator(a,b);cout<<"Sum is "<<sum<<"\n";return 0;}
Approach 2: Recursive
Java
public class TwoNumberSum {public static void main(String[] args) {int a = 7;int b = 8;int sum = addWithoutOperatorRecursion(a, b);System.out.println(sum);}private static int addWithoutOperatorRecursion(int a, int b) {if (b == 0)return a;elsereturn addWithoutOperatorRecursion(a ^ b, (a & a) << 1);}}
C++
#include <bits/stdc++.h>using namespace std;//function which add two number//without using + operatorint addWithoutOperatorRecursion(int a,int b){if(b==0)return a;elsereturn addWithoutOperatorRecursion(a^b,(a&b)<<1);}int main(){int a=7,b=8;int sum=addWithoutOperatorRecursion(a,b);cout<<"Sum is "<<sum<<"\n";return 0;}
No comments:
Post a Comment