--- tags: LeetCode --- # 371. Sum of Two Integers Calculate the sum of two integers a and b, but you are not allowed to use the operator **+ and -** . Example 1: Input: a = 1, b = 2 Output: 3 Example 2: Input: a = -2, b = 3 Output: 1 --- 輸入範本如下 ```C# public class Solution { public int GetSum(int a, int b) { } } ``` 自我限制 , 不准使用 Linq 的 Sum 方法(雖然實際上 Sum 也有使用 + 號運算子實作XD) ```C# 40 ms 15.5 MB You are here! Your runtime beats 67.46 % of csharp submissions. public int GetSum(int a, int b) => new int[] { a, b }.Sum(); ``` ### 直覺想法 1. 非地回解法 ```C# 36 ms 14.6 MB You are here! Your runtime beats 92.82 % of csharp submissions. public int GetSum(int a, int b) { while (b != 0) { int carry = (a & b) << 1; int sum = a ^ b; a = sum; b = carry; } return a; } ``` 2. 地回解法 ```C# 36 ms 14.6 MB You are here! Your runtime beats 92.82 % of csharp submissions. public int GetSum(int a, int b) { if (b == 0) { return a; } int carry = (a & b) << 1; int sum = a ^ b; return GetSum(sum, carry); } ``` ### 參考資源 [LeetCode 371. Sum of Two Integers](https://skyyen999.gitbooks.io/-leetcode-with-javascript/content/questions/371md.html) ### Thank you! You can find me on - [GitHub](https://github.com/s0920832252) - [Facebook](https://www.facebook.com/fourtune.chen) 若有謬誤 , 煩請告知 , 新手發帖請多包涵 # :100: :muscle: :tada: :sheep: