标签:位运算
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.
题意:计算a+b,但是不许使用+和-
public class Solution {
public int getSum(int a, int b) {
//第一种
while(a!=0){
int carry=(a&b)<<1;
b=a^b;
a=carry;
}
return b;
////递归计算
// if(b==0)return a;
// int carry=(a&b)<<1;
// int sum=a^b;
// return getSum(sum,carry);
}
}其实针对第一种方法,看图中就明白了。一开始搞乱了。
异或求得是俩数的无进位加法,而进位只会发生在1+1的时候,所以可以用&运算符,但是要左移一位。
就是这样,学习了。第一次做位运算。
Leetcode 371. Sum of Two Integers JAVA语言
标签:位运算
原文地址:http://fulin0532.blog.51cto.com/6233825/1890223