Leetcode 371. Sum of Two Integers
Given two integers a
and b
, return the sum of the two integers without using the operators +
and -
.
*
or /
?
+
and -
, but doesn’t mention other operators. However, ideally, we should avoid using any direct arithmetic operators to simulate addition.This problem can be solved by using bitwise operations. The process involves two key operations:
a
and b
and store it in a
. This gives the sum of a
and b
without the carry.a & b
and left shift it by 1 (<< 1
).b
with the carry.b
becomes zero.class Solution {
public:
int getSum(int a, int b) {
while (b != 0) {
// Calculate the sum without carry
int sum = a ^ b;
// Calculate the carry
int carry = (a & b) << 1;
// Update a to sum and b to carry
a = sum;
b = carry;
}
return a;
}
};
This solution utilizes bitwise operations to perform the addition iteratively and efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?