leetcode-sum-of-two-integers

题目大意

  https://leetcode.com/problems/sum-of-two-integers/

  求两个整数加法,不允许用+-

题目分析

  题目给的方法返回值已经默认了不会整数越界,所以就不用考虑了,直接就是按位计算就行

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public int getSum(int a, int b) {
int ans = 0;
int add = 0;
for (int i = 0; i < 32; i++) {
int ai = (a & 1);
int bi = (b & 1);
int tmp = ai + bi + add;
ans += ((tmp % 2) << i);
add = tmp / 2;
a >>= 1;
b >>= 1;
}
return ans;
}
}