A + B 問題
給出兩個整數a和b, 求他們的和, 但不能使用 +
等數學運算符。
直接上源碼
C++解法:
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, try to do it without arithmetic operators.
if(a==0) return b; //不再進位
if(b==0) return a; //不進位操作爲零,直接取進位操作的結果
int sum,i;
i=a^b; //不進位相加的結果
sum=(a&b)<<1; //進位的結果
return aplusb(sum,i); // 兩者再進行相加
}
}
Python解法:class Solution:
# """
# @param a: An integer
# @param b: An integer
# @return: The sum of a and b
# """
def aplusb(self, a, b):
# write your code here
if(a==0) :
return (b)
if(b==0) :
return (a)
i=a^b
sum = (a&b)<<1
return self.aplusb(i, sum)