371. Sum of Two Integers (Easy)

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 1:

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

Example 2:

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

Solutions

class Solution {

    public int getSum(int a, int b) {
        while (b != 0) {
            // c is formed by the same 1 bits of a and b through each bit
            int c = a & b;

            // a is formed by different 0/1 bits of a and b through each bit
            a = a ^ b;

            // When c is left shifted by 1 bit, it is the carry.
            b = c << 1;

            // in spite of the new a, b, previous a + b = current a + b, the sum is the same
        }

        return a;
    }
}

Incorrect Solutions

References

  1. https://www.programcreek.com/2015/07/leetcode-sum-of-two-integers-java/
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-03-22 00:57:11

results matching ""

    No results matching ""