aboutsummaryrefslogtreecommitdiff
path: root/sum_two_integers.c
blob: 4fee7e9a573cfa4b1a1bbab75b989fdda583e454 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 371. Sum of Two Integers
#include "leetcode.h"

/*
 * given two integers 'a' and 'b', return the sum of the two integers without
 * using the operators '+' and '-'.
 */

int getSum(int a, int b) {
  int trigger = a & b, ans = a ^ b;
  while (trigger) {
    int carry = (trigger & 0xFFFFFFFF) << 1;
    trigger = carry & ans;
    ans ^= carry;
  }
  return ans;
}

int main() {
  printf("%d\n", getSum(1, 2)); // expect: 3
  printf("%d\n", getSum(2, 3)); // expect: 5
}