Created
March 30, 2018 13:51
-
-
Save tamarous/49e8efc6cfc38687a4db78ee84853a0f to your computer and use it in GitHub Desktop.
使用位运算实现两个数的加减乘法
This file contains hidden or 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) { | |
int sum = 0; | |
while(b != 0) { | |
sum = a ^ b; | |
b = (a & b) << 1; | |
a = sum; | |
} | |
return sum; | |
} | |
// 减法 | |
int negNum(int n) { | |
return getSum(1, ~n); | |
} | |
int minus(int a, int b { | |
return getSum(a, negNum(b)); | |
} | |
// 乘法 | |
int multi(int a, int b) { | |
int res = 0; | |
while(b != 0) { | |
if ((b & 1) != 0) { | |
res = getSum(res, a); | |
} | |
a = a << 1; | |
b = b >> 1; | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment