---
title: 'LeetCode 371. Sum of Two Integers'
disqus: hackmd
---
# LeetCode 371. Sum of Two Integers
## Description
Given two integers a and b, return the sum of the two integers without using the operators + and -.
## Example
Input: a = 1, b = 2
Output: 3
Input: a = 2, b = 3
Output: 5
## Constraints
-1000 <= a, b <= 1000
## Answer
此題可用bit operation來實現,以加法器的概念來實作,取XOR為疊加,取AND為須進位項,以迴圈來循環操作到不需進位為止。
```Cin=
// 2022_04_05
int getSum(int a, int b){
int and = 0, xor = 0;
while(a&b){
// 轉成unsigned int 可以容納32位,如此才能計算左移一位,
// 轉回int為最高位導致變回符號位,
and = ((unsigned int)(a&b)) << 1;
xor = a ^ b;
a = and;
b = xor;
}
return a | b;
}
```
## Link
https://leetcode.com/problems/sum-of-two-integers/
###### tags: `Leetcode`