Write a function that add two numbers A and B. You should not use +
or any arithmetic operators.
Notice
There is no need to read data from standard input stream. Both parameters are given in function aplusb
, you job is to calculate the sum and return it.
Are a and b both 32-bit
integers?
- Yes.
Can I use bit operation?
- Sure you can.
Given a=1
and b=2
return 3
编写一个函数,添加两个数字A和B.您不应该使用+或任何算术运算符。
注意
不需要从标准输入流中读取数据。两个参数都在函数中给出aplusb,您的工作是计算总和并返回它。
澄清
a和b都是32-bit整数吗?
是。
我可以使用位操作吗?
你当然可以。
例
鉴于a=1与b=2回报3
位操作(是对二进制进行操作)
& 与 同为1,显示为1。
| 或 同为0,显示为0。
^ 异或 相同为0,想异为1.。
~ 取反 0->1,1->0。
<< 左移 向左进位。
位操作进行加法的算法大概分为两步:
1. 做异或操作,得到不同的位,得到另一个值(不考虑进位,直接得出计算结果)
2. 做与操作,得到相同的位,左移进位得到一个值(进位,用二进制表示)
若两个值中有一个为0,那么结果就是另一个。
int aplusb(int a, int b)
{
int x, y;
x = a;
y = b;
while(x != 0 && y != 0)
{
x = a ^ b;
y = (a & b) << 1;
a = x;
b = y;
}
return x==0?y:x;
}
举例:x = 1,y = 2,结果为3。
x二进制为01,y二进制位10.
1-- x = a^b x 二进制表示11,为3.
2-- y = (a & b) << 1 a & b = 00 左移1位,y二进制表示000,为0。
2018/1/22