리트코드

[leetcode] Sum of Two Integers

컴공코딩러 2022. 12. 26. 04:14

문제 

Given two integers a and b, return the sum of the two integers without using the operators + and -

 

어떻게 풀지 고민하다 비트 연산자 라는건 생각을 했는데 계속 틀려서 답을 봐버림

 

 

def getSum(a, b):
    mask = 0xffffffff
    while (b & mask > 0):
        carry = (a & b) << 1
        a = a ^ b
        b = carry
    return (a & mask) if b > 0 else a

마지막 return 부분이 왜 저럴까 생각하고 음수를 넣어서 디버깅 돌려보니 이해가됨...(사실 100%는 안됨)

 

이런거 풀때마다 머리가 아프다.....