Skip to content

Instantly share code, notes, and snippets.

@tamarous
Created March 30, 2018 13:51
Show Gist options
  • Save tamarous/49e8efc6cfc38687a4db78ee84853a0f to your computer and use it in GitHub Desktop.
Save tamarous/49e8efc6cfc38687a4db78ee84853a0f to your computer and use it in GitHub Desktop.
使用位运算实现两个数的加减乘法
// 加法
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