位运算

运算符

基本的位操作符有六种:与、或、异或、取反、左移、右移。*

运算符 运算规则
&(与) 两个位同为1时,结果才为1
/(或) 两个位同为0时,结果才为0
^(异或) 两个位相同为0,相异为1
~(取反) 0变1,1变0
<<(左移) 各二进制位全部左移若干位,高位丢弃,低位补0
>> (右移) 各二进制位全部右移若干位,低位丢弃。对无符号数,高位补0;有符号数,正数补0负数补1

A+B问题

问题描述

Markdown

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
/**
* @param a: An integer
* @param b: An integer
* @return: The sum of a and b
*/
public int aplusb(int a, int b) {
// write your code here
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);
}
}