Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- sum of 010 and 101 is 111 and xor of 010 and 101 is also same.
- but sum and xor of 001 and 001 is not same because lsb bits sum ie. 1+1 =0 and 1 carry.
- so we will do xor of a and b in a so a will be having the sum of those bits where there
- is no carry.we can find the carry bits using & opearator.ofcourse we shift carry while
- sum 1 bit so do the same and add carry again.
- Here we are using unsigned for keeping that is must otherwise shifting will go overflow.
- */
- class Solution {
- public:
- int getSum(int a,int b) {
- unsigned int carry;
- while(b!=0){
- carry=a&b;
- a=a^b;
- b=(carry)<<1;
- }
- return a;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement