Q:
Calculate the sum of two integers a and b, but you are not allowed to use the operator
+
and -
.
Example:
Given a = 1 and b = 2, return 3.
Given a = 1 and b = 2, return 3.
A:
就是按位亦或,再把进位右移,继续运算public class Solution { public int getSum(int a, int b) { if(b==0) return a; int carry = a & b; a = a^b; return getSum(a, carry<<1); } }
No comments:
Post a Comment