原题网址:https://leetcode.com/problems/sum-of-two-integers/
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
方法:手工实现二进制加法。
public class Solution {
public int getSum(int a, int b) {
int sum = a ^ b;
int carry = a & b;
while (carry != 0) {
carry <<= 1;
int ncarry = sum & carry;
sum ^= carry;
carry = ncarry;
}
return sum;
}
}

本文介绍了一种不使用+和-运算符计算两个整数之和的方法。通过位操作实现了二进制加法,提供了完整的Java代码实现。
756

被折叠的 条评论
为什么被折叠?



