From 8f4256dd97fe3ad442443201a9b893de80859c96 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 10 Mar 2025 18:40:27 -0600 Subject: 371. sum of two integers --- sum_two_integers.c | 22 ++++++++++++++++++++++ sum_two_integers.py | 23 +++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 sum_two_integers.c create mode 100644 sum_two_integers.py diff --git a/sum_two_integers.c b/sum_two_integers.c new file mode 100644 index 0000000..4fee7e9 --- /dev/null +++ b/sum_two_integers.c @@ -0,0 +1,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 +} diff --git a/sum_two_integers.py b/sum_two_integers.py new file mode 100644 index 0000000..1ed3424 --- /dev/null +++ b/sum_two_integers.py @@ -0,0 +1,23 @@ +# 371. Sum of Two Integers + +""" +given two integers 'a' and 'b', return the sum of the two integers without +using the operators '+' and '-'. +""" + + +class Solution(object): + def getSum(self, a, b): + """ + :type a: int + :type b: int + :rtype: int + """ + ab = [a, b] + return sum(ab) + + +if __name__ == "__main__": + obj = Solution() + print(obj.getSum(a=1, b=2)) + print(obj.getSum(a=2, b=3)) -- cgit v1.2.3