Returns the sum of two integers without the use of the four-character operator.

Source: Internet
Author: User

Here I only write the key code:

Int add (int n, intm)

{
If (M = 0) returnn; ①

Int sum = n ^ m; ②

Int carry = (N & M) <1; ③

Return add (sum, carry); ④
}

Before analyzing the code in each step, let's look at two examples:
The sum of two numbers without bits:
0000 0010------2
0000 0100------4
The result is:
0000 0110------6
Add the two numbers of incoming bits:
0000 0101------5
0000 0100------4
The result is:
20171001------9
First, we will introduce these two examples into the function to understand the execution process of the function by comparing the differences between the carry operation and the non-carry operation.

Define an add function and declare the two integer variables:
① When one of M and N is 0, the result returns another value. This statement is the final exit of the program.

② N and M perform an exclusive or operation. If m and n are not included in the sum, sum is the result. Otherwise, save the numeric value without carry. Continue with the following carry operation.

③ M and N perform phase and operation, and then shift 1 bit left. When a carry value is generated, m and n are 1 at the same time at the same position, and 1 at the end of the phase, and 1 at the left to get the carry value. The second and above carry, and so on. If there is no carry, carry is 0.

④ Recursive function return add (), and perform a similar operation on the sum and carry obtained by the preceding steps until no carry is generated, that is, carry = 0.

Note: If the analysis is incorrect, we hope you can point it out!

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.