中文题
使用 位运算 求 a 和 b 的和
两个整数a和b,其中0≤a, b≤100。
提示:
a+b = a ^ b + (a&b)<<1
挑战:
去除约束条件 0<=a,b<=100
不使用运算符 + , -
英文题
The sum of a and b using bit operations
Two integer a,b while 0<=a,b<=100
Hint:
a+b = a ^ b + (a&b)<<1
Challenge:
Get rid of 0<=a,b<=100
Don’t use + and -
解Java
public class Solution {
public int sum(int a, int b) {
if (b == 0) {
return a;
}
if (a == 0) {Í
return b;
}
int sum = a ^ b;
int carry = (a & b) << 1;
return sum(sum, carry);
}
}
python解
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
if a == 0:
return b
if b == 0:
return a
while b != 0:
carry = a & b
a = a ^ b
b = carry << 1
return a
c ++解
*/
class Solution
{
public:
int sum(int a, int b)
{
if (a == 0)
{
return b;
}
if (b == 0)
{
return a;
}
int sum = a ^ b;
int carry = (a & b) << 1;
return sum(sum, carry);
}
}
JavaScript
/**
* A+B Problem
* a加b
*/
/**
* @param {number} a
* @param {number} b
* @return {number}
*/
var getSum = function (a, b) {
if (a === 0) {
return b
}
if (b === 0) {
return a
}
let temp = a ^ b
let result = (a & b) << 1
return result + temp
};