[Leetcode] Sum of two integers--using bitwise operations to implement addition operations

Source: Internet
Author: User
Tags bitwise

Problem:

thesumoftwoaandnottotheanda1and2return3.

Analysis:

This requires that we do not use addition, subtraction and other operators to implement the addition operation. This should be done by using bitwise operations, which is, in fact, the implementation of the addition operation within the CPU of the computer.
x XOR y truth table:
X y output
0 0 0
0 1 1
1 0 1
1 1 0

X and Y truth table:
X y output
0 0 0
0 1 0
1 0 0
1 1 1
We can use & and ^ operations to achieve addition based on the truth table above, and each of the ^ operations gets the non-rounding of each one and the carry of each bit with the & operation.

According to the above analysis, we can add each x, Y and each one to perform XOR and and operations, and then get the final result. But if you want to get each bit, you also use the and operation.
Say 00001010,
To take the second-lowest value (1), the value is: 00001010&00000010
To take the third-lowest value (0), the value is: 00001010&00000100
To take the fourth-lowest value (1), the value is: 00001010&00001000

And that's not really going to get the value on each one, but also the action.

First, we get the carry on each one by doing a & bit operation on X and Y. The x and y are then performed with the ^ bitwise operation, resulting in no added and rounding. Finally, the resulting and as New X, the resulting carry to the left one (the 0th digit of the carrying input is 0) as the new Y, continue to do the above steps until the rounding is 0, at which point the X and Y are saved is the same.

Code:

class  solution  { public : int  getsum (int  A, int  b) {int  sum  = A;        int  icarry = b; while         (Icarry!=0 )             {int  tmp = sum ;             sum  = tmp ^ Icarry;        Icarry = (tmp&icarry) <<1 ;    } return  sum ; }};

[Leetcode] Sum of two integers--with bitwise operations for addition operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.