您的位置:首页 > 其它

A + B Problem

2016-03-12 15:15 330 查看
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.

Clarification

Are a and b both
32-bit
integers?

Yes.

Can I use bit operation?

Sure you can.

Example
Challenge
Tags
Notes

Given
a=1
and
b=2
return
3


主要利用异或运算来完成
// 异或运算有一个别名叫做:不进位加法
// 那么a ^ b就是a和b相加之后,该进位的地方不进位的结果
// 然后下面考虑哪些地方要进位,自然是a和b里都是1的地方
// a & b就是a和b里都是1的那些位置,a & b << 1 就是进位
// 之后的结果。所以:a + b = (a ^ b) + (a & b << 1)
// 令a' = a ^ b, b' = (a & b) << 1
// 可以知道,这个过程是在模拟加法的运算过程,进位不可能
// 一直持续,所以b最终会变为0。因此重复做上述操作就可以
// 求得a + b的值。

/**
* Created by JZloveSnow on 16/3/12.
*/
class Solution24 {
public int aplusb(int a, int b) {
int result=0;
while (b != 0) {
int tempa = a^b;
int tempb = (a&b)<<1;
a = tempa;
b = tempb;
}
return a;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: