Skip to content

Instantly share code, notes, and snippets.

@yigger
Created March 5, 2017 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yigger/1fc36cf0ae9343cce6738bcd5bb7266a to your computer and use it in GitHub Desktop.
Save yigger/1fc36cf0ae9343cce6738bcd5bb7266a to your computer and use it in GitHub Desktop.
计算两个数的和不用+-*/
/*递归版本
*/
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