Advertisement
imashutosh51

Sum of Two Integers

Oct 16th, 2022
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. /*
  2. Logic:
  3. sum of 010 and 101 is 111 and xor of 010 and 101 is also same.
  4. but sum and xor of 001 and 001 is not same because lsb bits sum ie. 1+1 =0 and 1 carry.
  5. so we will do xor of a and b in a so a will be having the sum of those bits where there
  6. is no carry.we can find the carry bits using & opearator.ofcourse we shift carry while
  7. sum 1 bit so do the same and add carry again.
  8.  
  9. Here we are using unsigned for keeping that is must otherwise shifting will go overflow.
  10. */
  11.  
  12. class Solution {
  13. public:
  14.     int getSum(int a,int b) {
  15.         unsigned int carry;
  16.         while(b!=0){
  17.             carry=a&b;
  18.             a=a^b;
  19.             b=(carry)<<1;
  20.         }
  21.         return a;
  22.     }
  23. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement