leetcode 开始收费了,开始转战lintcode。
Write a function that add two numbers A and B. You should not use + or any arithmetic operators.
Clarification
Are a and b both 32-bit integers?
Yes.
Can I use bit operation?
Sure you can.
Example
Given a=1 and b=2 return 3
让你计算两数之和,条件是不准用+运算符,首先想到是a+b = (a^2-b^2)/(a-b). 这样做完全符合条件,但是不是题目本身想考察的,bit operation提示我们可能要用到位运算,谷歌了一下,a+b可以通过位运算描述为:
a = a^b --------> a,b异或,表示不带进位的相加. (1)
b = (a&b)<<1 ------> a,b相与后左移,表示进位 (2)
重复上面的步骤,直到b为0, 此时a的值即为所求. 不过这种方法的runtime更·长一些.
两种方式的代码:
int aplusb(int a, int b) {
// write your code here
int temp;
while(b != 0){
temp = a&b;
a = a^b;
b = temp<<1;
}
return a;
}
int aplusb(int a, int b) {
// write your code here
if(a == b)
return 2*b;
int temp = a*a-b*b;
return temp/(a-b);
}