不用加减乘除做加法

题目描述

写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。

我的解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
public int Add(int num1,int num2) {
int n1, n2;
n1 = (num1 & num2) << 1;
n2 = num1 ^ num2;
while((n1&n2) != 0) {
num1 = n1;
num2 = n2;
n1 = (num1 & num2) << 1;
n2 = num1 ^ num2;
}
return n1 | n2;
}
}