Created
March 5, 2017 15:07
-
-
Save yigger/1fc36cf0ae9343cce6738bcd5bb7266a to your computer and use it in GitHub Desktop.
计算两个数的和不用+-*/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*递归版本 | |
*/ | |
int getSum(int a, int b) { | |
return b == 0 ? a : getSum(a^b, (a&b)<<1); | |
} | |
/*不递归版本 | |
int getSum(int a, int b) { | |
int sum = a; | |
while (b != 0) | |
{ | |
sum = a ^ b;//calculate sum of a and b without thinking the carry | |
b = (a & b) << 1;//calculate the carry | |
a = sum;//add sum(without carry) and carry | |
} | |
return sum; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment