X + y = (X & Y) <1) + (x ^ y) proof

Source: Internet
Author: User

Method 1:
We consider adding X and Y to bits in binary representation.
Where the I-th Digit
XI + yi = (XI & Yi) <1) + (Xi ^ Yi)
(XI & Yi) <1 indicates that when XI and Yi are both 1, carry 1 is required.
Xi ^ Yi indicates that carry is not considered. The value of the current BIT.
Add all the data, that is
X + y = sum {Xi * 2 ^ I} + sum {Yi * 2 ^ I} = sum {(XI + yi) * 2 ^ I}
= Sum {(XI & Yi) <1) + (Xi ^ Yi) * 2 ^ I}
= Sum {(XI & Yi) * 2) * 2 ^ I + (Xi ^ Yi) * 2 ^ I}
= Sum {(XI & Yi) * 2 ^ I} * 2 + sum {(Xi ^ Yi) * 2 ^ I}
= (X & Y) * 2 + (x ^ y)
= (X & Y) <1) + (x ^ y)

Method 2:

X = (X & Y) + (x ^ y) & X)
Y = (X & Y) + (x ^ y) & Y)
(X ^ y) & x) + (x ^ y) & Y) = x ^ y
----------------------------------
X + y = 2 * (X & Y) + (x ^ y)

Application:

Implement Addition of two integers using bitwise operations

Int add (int A, int B) {If (B = 0) return a; int sun, carry; sum = a ^ B; // complete Step 1 without carry addition caryy = (A & B) <1; // complete Step 1 with a carry addition, and carry return add (sum, carry ); // perform recursive addition}

X + y = (X & Y) <1) + (x ^ y) proof

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.