Header Ad

Leetcode Sum of Two Integers problem solution

In this Leetcode Sum of Two Integers problem solution you are given two integers a and b, return the sum of the two integers without using the operators + and -.

Leetcode Sum of Two Integers problem solution


Problem solution in Python.

import math
class Solution:
    def getSum(self, a: int, b: int) -> int:
        return int(math.log(math.exp(a)*math.exp(b)))



Problem solution in Java.

public int getSum(int a, int b) {
    int carry =0;
    int result =0;
    int bit =0,count=0;
   while(count<32){
       int aa = a&1;
       a= a>>>1;
       int bb = b&1;
       b= b>>>1;
        bit =aa^bb^carry;
        result |= bit<<count++;
        if(aa==1 && bb==1) carry =1;
        else if(carry ==1 && aa==1) carry=1;
        else if(carry ==1 && bb ==1) carry =1;
        else carry =0;
   }
   return result;
    
}


Problem solution in C++.

class Solution {
public:
    int getSum(int a, int b) {
     
        int carry = 0;
        while(b!=0) {
            carry = a&b;
            a = a^b;
            b = carry << 1;
        }
        return a;
    }
};


Problem solution in C.

int getSum(int a, int b)
{

    while (b &= ~(a ^= b))
        b <<= 1;

    return a;
}


Post a Comment

0 Comments