lint0001 A + B Problem
2019-02-04 本文已影响0人
日光降临
Write a function that add two numbers A and B.
Of course you can just return a + b to get accepted. But Can you challenge not do it like that?(You should not use + or any arithmetic operators.)
public class Solution {
public int aplusb(int a, int b) {
// 异或运算有一个别名叫做:不进位加法
// 那么a ^ b就是a和b相加之后,该进位的地方不进位的结果
// 然后下面考虑哪些地方要进位,自然是a和b里都是1的地方
// a & b就是a和b里都是1的那些位置,a & b << 1 就是进位
// 之后的结果。所以:a + b = (a ^ b) + (a & b << 1)
// 令sum = a ^ b, carry = (a & b) << 1
// 可以知道,这个过程是在模拟加法的运算过程,进位不可能
// 一直持续,所以carry最终会变为0。因此重复做上述操作就可以
// 求得a + b的值。
while(b!=0){
int sum = a^b;
int carry = (a&b)<<1;
a = sum;
b = carry;
}
return a;
}
}
假设a=3, that is 0011, b=5, that is 0101,
a^b=0110, a&b<<1 = 0010, 他们两个再相加,重复这个过程,直到b,也就是进位为0
- python的解答,未知正确与否
class Solution:
def aplusb(self, a, b):
# write your code here
if a == b: return a <<1
if a == -b: return 0
while(b != 0):
tmpA = a^b
b = (a&b)<<1
a = tmpA
return a