371. Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = -2, b = 3
Output: 1

Rust Solution

struct Solution;

impl Solution {
    fn get_sum(a: i32, b: i32) -> i32 {
        if b == 0 {
            a
        } else {
            Self::get_sum(a ^ b, (a & b) << 1)
        }
    }
}

#[test]
fn test() {
    assert_eq!(Solution::get_sum(1, 2), 3);
    assert_eq!(Solution::get_sum(-2, 3), 1);
}

Having problems with this solution? Click here to submit an issue on github.