Do not use subtraction to do the problem of addition

Source: Internet
Author: User

Title: Implement the int add (int a, int b) method to implement the sum of A and B, but do not allow arithmetic operations such as +-*/to be used internally.

Answer: This question is actually how to do the addition of computer hardware. The addition and multiplication in the computer is the method of simulating the addition and multiplication of the man to design and implement the CPU arithmetic operation module. This should be learned when we learn the principles of computer composition. As in the following example:

1101
11
+
--------------
10000

This calculation can be divided into two parts, part of the bitwise + process, and the other part is the process of rounding.

Bitwise +, in fact, is the XOR operation, 1+1=0, 1-bit, 0+1=1+0=1,0+0=0

How does the carry count? In what case carry, when the only carry, you should immediately be able to think and operation. Added to the high to continue the next operation. Then we can get the following formula:

a+b=a^b+ (a&b) <<1

It also uses the addition, cannot solve our problem, but you do not think this is a recursion?

Add (A, b) =add (A^b, (a&b) <<1)

So when does this recursion end? Obviously, one of a or B is 0, and surely it can be terminated.

Here's the code:

int add (int a, int b) {    if (!a) return B;    else         return Add ((A & B) << 1, a ^ b);}

Do not use subtraction to do the problem of addition

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.