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.
不能用运算符,只能考虑位运算,按位与并左移一位可以找出需要进位的位,按位异或可以确定每位的值。
public int getSum(int a, int b) { while(b!=0){ int c=a^b; b=(a&b)<<1; a=c;} return a; }