Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
25 lines (19 loc) · 633 Bytes

371.md

File metadata and controls

25 lines (19 loc) · 633 Bytes

371. Sum of Two Integers

Description

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

Example: Given a = 1 and b = 2, return 3.

Thinking Process

  1. At each iteration, calculate the carry bits and the addition result(with no carry) separately
  2. At next iteration, shift the carry result from last iteration left by 1 and add it to the addition result
public int getSum(int a, int b) {
    //store result in a, store carry in b
    while(b != 0){
        int carry = a & b;
        a = a ^ b;
        b = carry << 1;
    }
    return a;
}