- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum of Two Integers in Python
Suppose we have two integers a and b. Our task is to find the sum of these two integers. One constraint is that, we cannot use any operator like + or -. So if a = 5 and b = 7, the result will be 12.
To solve this, we will follow these steps −
- For solving we will use the bitwise logical operators
- If b = 0, then return a
- otherwise, recursively use the sum function by providing an XOR b, and a AND b after left shifting the result one time
Example (Python)
Let us see the following implementation to get a better understanding −
#include <iostream> using namespace std; class Solution { public: int getSum(int a, int b) { return b == 0?a:getSum(a^b, (unsigned int)(a&b)<<1); } }; main(){ Solution ob; cout<<ob.getSum(5,7)<<endl; }
Input
a = 5 b = 7
Output
12
Advertisements