Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example 1:
Input: a = 1, b = 2
Output: 3
Approach
Java
public class SumofTwoIntegers {public static void main(String[] args) {int a = 1, b = 2;System.out.println(getSum(a, b));}static int getSum(int a, int b) {// base caseif (a == 0)return b;// base caseif (b == 0)return a;int sum = a ^ b;int carry = (a & b) << 1;return getSum(sum, carry);}}
C++
#include <bits/stdc++.h>using namespace std;int getSum(int a, int b){//base caseif (a == 0)return b;//base caseif (b == 0)return a;int sum = a ^ b;int carry = (unsigned int)(a & b) << 1;return getSum(sum, carry);}int main(){int a = 1, b = 2;cout << getSum(a, b);return 0;}
No comments:
Post a Comment