Leetcode 371. Sum of Two Integers
Leetcode 371: Sum of Two Integers
Given two integers a and b, return the sum of the two integers without using the operators + and -.
a and b will be within the range of a typical 32-bit signed integer: ([-2^{31}, 2^{31} - 1]).a and b are always valid integers?
a and b are within the 32-bit signed integer range.To calculate the sum of two integers without using + or -, we can use bitwise operations:
^ (XOR) operator since 1 XOR 1 = 0, 1 XOR 0 = 1, 0 XOR 1 = 1, and 0 XOR 0 = 0.& (AND) operator followed by a left shift <<, since carry = (a & b) << 1. This handles the carry operation in binary addition.a to be the sum (without carry) and b to be the carry. This process continues until b becomes zero.class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1; // Calculate carry
a = a ^ b; // Calculate sum without carry
b = carry; // Assign carry to b
}
return a;
}
}
This approach effectively computes the sum of two integers using bitwise operations while adhering to the constraints provided in the problem statement.
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?