From aa0af75113ce39e946be4b37580c2887e5357571 Mon Sep 17 00:00:00 2001 From: Tanishkcodes Date: Tue, 7 Oct 2025 08:01:49 +0530 Subject: [PATCH 1/2] Create SumOfTwoIntegers short method It is the shortest method to solve this DSA problem using recursion --- .../cpp/sumOfTwoIntegers/SumOfTwoIntegers short method | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers short method diff --git a/algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers short method b/algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers short method new file mode 100644 index 000000000..b3dffa1af --- /dev/null +++ b/algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers short method @@ -0,0 +1,7 @@ +// Short method for sum of two integers +class Solution { +public: + int getSum(int a, int b) { + return b == 0 ? a : getSum(a ^ b, (unsigned)(a & b) << 1); + } +}; From 541d7e875a322254125c8f58eca0501c234d621b Mon Sep 17 00:00:00 2001 From: Tanishkcodes Date: Tue, 7 Oct 2025 08:03:36 +0530 Subject: [PATCH 2/2] Update SumOfTwoIntegers short method Shortest method to solve this DSA problem with its explanation --- .../SumOfTwoIntegers short method | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers short method b/algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers short method index b3dffa1af..0982498d6 100644 --- a/algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers short method +++ b/algorithms/cpp/sumOfTwoIntegers/SumOfTwoIntegers short method @@ -1,7 +1,24 @@ // Short method for sum of two integers +// Define a class named Solution class Solution { public: + // Function to find the sum of two integers without using '+' or '-' int getSum(int a, int b) { - return b == 0 ? a : getSum(a ^ b, (unsigned)(a & b) << 1); + + // Base case: if b is 0, there is no carry left + // So the result is simply 'a' + return b == 0 + ? a // If b == 0, return a + : getSum( + a ^ b, // Step 1: a XOR b gives sum without carry + (unsigned)(a & b) << 1 // Step 2: a AND b gives carry, shift left by 1 + ); + /* + Explanation: + 1. a ^ b → XOR operation adds bits where only one of them is 1 (ignores carry) + 2. a & b → AND operation finds positions where both bits are 1 (this is the carry) + 3. << 1 → shift carry left by 1 to add it in the next higher bit + 4. Recursive call → we repeat the process until carry (b) becomes 0 + */ } };