꿀잠마스터 2026. 9. 4. 01:47

https://leetcode.com/problems/sum-of-two-integers/description/

 

Sum of Two Integers - LeetCode

Can you solve this real interview question? Sum of Two Integers - Given two integers a and b, return the sum of the two integers without using the operators + and -.   Example 1: Input: a = 1, b = 2 Output: 3 Example 2: Input: a = 2, b = 3 Output: 5   Co

leetcode.com

 

"+", "-" 없이 주어지 두 수의 합계를 구하는 문제이다. 비트 연산자를 이용하여 해결해야 한다.

 

십진수를 더할 때 자리수 별로 더하고 다음 자릿수로 넘겨서 더해주는 방식에 착안해서 해결해보았다. "^" 연산자를 사용해서 0과 1의 합계를 더해주고, "&" 연산자를 사용해서 1과 1의 합계 부분을 구한 이후 자릿수 올리기를 반복해주었다. 최종 코드는 아래와 같이 하여 통과하였다.

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