【发布时间】:2016-11-04 21:24:17
【问题描述】:
我相信计算机必须借助按位左移运算符的异或来实现它。对吗?
这是java中的实现
public class TestAddWithoutPlus {
public static void main(String[] args) {
int result = addNumberWithoutPlus(6, 5);
System.out.println("result is " + result);
}
public static int addNumberWithoutPlus(int a, int b) {
if (a == 0) {
return b;
} else if (b == 0) {
return a;
}
int result = 0;
int carry = 0;
while (b != 0) {
result = a^b; // SUM of two bits is A XOR B
carry = (a&b); // CARRY is AND of two bits
carry = carry << 1; // shifts carry to 1 bit to calculate sum
a=result;
b=carry;
}
return result;
}
}
【问题讨论】:
-
你有什么问题?
-
只是想确认计算机内部采用类似的算法进行添加操作?
-
计算机在硬件中使用了一系列只能在软件中模拟的门。实际上,加法只需要一个时钟周期即可完成所有操作。
标签: java c algorithm computer-science