371. Sum of Two Integers

JJ·2021년 1월 3일
0

Algorithms

목록 보기
44/114
class Solution:
    def getSum(self, a: int, b: int) -> int:
        sign = 1
        
        if (abs(b) > abs(a)):
            return self.getSum(b, a)
        
        if (a * b < 0):
            if (a < 0):
                sign = -1
        
        if (a < 0 and b < 0):
            sign = -1
    
        num = math.sqrt(a * a + 2 * a * b + b * b)
        return int(num * sign);

Runtime: 24 ms, faster than 93.47% of Python3 online submissions for Sum of Two Integers.
Memory Usage: 14.1 MB, less than 64.14% of Python3 online submissions for Sum of Two Integers.

되긴 하는데 더하기를 아예 쓰면 안된다..

class Solution:
    def getSum(self, a: int, b: int) -> int:
        x, y = abs(a), abs(b)
        if (x < y):
            return self.getSum(b, a)
        
        sign = 1 if a > 0 else -1
        
        if a * b >= 0:
            while y:
                answer = x ^ y
                carry = (x & y) << 1
                x, y = answer, carry
        else:
            while y:
                answer = x ^ y
                borrow = ((~x) & y) << 1
                x, y = answer, borrow
        return x * sign

이렇게 풀어야 한다고 하네요
binary operator!

Runtime: 32 ms, faster than 38.95% of Python3 online submissions for Sum of Two Integers.
Memory Usage: 14.2 MB, less than 38.81% of Python3 online submissions for Sum of Two Integers.

0개의 댓글