371. Sum of Two Integers (Binary)

https://leetcode.com/problems/sum-of-two-integers/discuss/84277/One-liner-with-detailed-explanation

https://stackoverflow.com/questions/9070937/adding-two-numbers-without-operator-clarification

sum用^把不需要进位的取出
carry把需要进位的用<<实现进位 然后再把sum和carry相加算出进位之后的结果 知道carry为0 就是没有需要进位的了

 1 class Solution {
 2     public int getSum(int a, int b) {
 3         if (b == 0) return a;
 4         int sum, carry;
 5         sum = a ^ b;
 6         carry = (a & b) << 1;
 7         return getSum(sum, carry);
 8         
 9     }
10 }

猜你喜欢

转载自www.cnblogs.com/goPanama/p/9398886.html