(written question) The addition operation is only realized by logical operation

Source: Internet
Author: User

Topic:

As shown in title

Ideas:

Logical operations, binary operations, are not related to &, or |, non-, XOR, and shift >>,<<.

In addition, in decimal, only the bitwise add and carry two operations.

The same is true from the binary angle, where the bit bits are added together with the corresponding carry.

1, bit bits add, through the logical operation of the XOR operation can be achieved, such as 0+1=1,1+0=1,0+0=0;

2, carry operation, through the operation of the logical operation can be achieved, such as 1+1=1, because carry is toward the high +1, so need to move the result of the left one bit.

The addition operation of the above two operations is the result of the addition operation, which is a recursive process, which can also be realized by non-recursive loop.

For a+b, equivalent to (a^b) + (a&b) <<1

Code:
#include <iostream>using namespace std;//recursive methodint add_1 (int num1,int num2) {    if (num1==0)        return num2;    if (num2==0)        return NUM1;    int num_xor=num1^num2;    int carry= (num1&num2) <<1;    Return Add_1 (Num_xor,carry);} Non-recursive methodint add_2 (int num1,int num2) {    int sum=0;    int num3=0;    int num4=0;    while (num1&num2) {        num3=num1^num2;        num4= (num1&num2) <<1;        num1=num3;        num2=num4;    }    sum=num1^num2;    return sum;} int main () {    int num1=100;    int num2=200;    cout << add_1 (num1,num2) << Endl;    cout << add_2 (num1,num2) << Endl;    return 0;}

  

(written question) The addition operation is only realized by logical operation

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.