An interview question about how computers do addition

Source: Internet
Author: User

Question: implement the int add (int a, int B) method to implement the sum of a and B, but internal arithmetic operations such as +-*/are not allowed.

Answer: This question is actually about how to add computer hardware. The addition and multiplication in the computer simulate the addition and multiplication methods to design and implement the cpu arithmetic operation module. This should be learned in our course on computer composition principles. For example:

1101

11

+

--------------

10000

This computation can be divided into two parts: the bitwise + process and the carry process. Bitwise + is actually an exclusive or operation. 1 + 1 = 0, first digit, 0 + 1 = 1 + 0 = 1, 0 + 0 = 0. How can we calculate the carry? Under what circumstances is the carry-in and 1 + 1 time? You should be able to think about it immediately. The bit to be added to the high level to continue to participate in the next operation. We can get the following formula:

A + B = a ^ B + (a & B) <1

We still use addition, which cannot solve our problem, but do you think this is a recursion?

Add (a, B) = add (a ^ B, (a & B) <1)

When will this recursion end? Obviously, if one of a or B is 0, it can be terminated.

The following code is used:

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


This article from the "Yi fall Dusk" blog, please be sure to keep this source http://yiluohuanghun.blog.51cto.com/3407300/1294327

Related Article

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.