版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011964923/article/details/78834571
来源: lintcode A+B问题
解决方法 :位操作
六种按位操作符:
- 按位与:&
- 按位或:|
- 按位取反:~
- 按位异或:^
- 按位左移:<< (高位丢弃,低位补零)
- 按位右移:>> (对无符号数,高位补0,有符号数,各编译器处理方法不一样,有的补符号位(算术右移),有的补0(逻辑右移))
解决加法问题
a^b; 得到不含进位之和
(a&b)<<1; 进位
只要进位不为零,则迭代;否则返回
// java
public class Solution {
/*
* @param : An integer
* @param : An integer
* @return: The sum of a and b
*/
public int aplusb(int a, int b) {
int sum_without_carry, carry;
sum_without_carry = a^b; //没有进位的和
carry = (a&b)<<1; //进位
if(carry==0)
return sum_without_carry;
else
return aplusb(sum_without_carry, carry);
}
};