[Careercup] 18.1 Add Numbers two number add

Source: Internet
Author: User
Tags add numbers

18.1 Write A function that adds the numbers. You should don't use + or any arithmetic operators.

This problem allows us to add two numbers, but we can not use a plus or some other mathematical symbols, then we can only return to the nature of computer operations, bit manipulation, when we do the addition, each bit of the sum may have a carry carry generated, Then we need to add the rounding to the next calculation, so can we take two parts apart, let's look at an example 759+674

1. If we do not consider rounding, we can get 323

2. If we only consider rounding, we can get 1110

3. We put the above two digital holidays 323+1110=1433 is the final result

Then we further analyze, if we get the first second case above, we look at the binary, do not consider the Add, 0+0=1, 0+1=1, 1+0=1, 1+1=0, this is the operating rules of the XOR, if only consider the add 0+0=0, 0+1=0, 1+0=0, 1+1= 1, and this is actually the operation, and the third step in adding the two, we recursively call this algorithm, the termination condition is when carry is 0 o'clock, we directly return the result of the first step, see the code as follows:

int Add (intint  b) {    if0return  A;     int sum = a ^ b;     int 1 ;     return Add (sum, carry);}

Careercup all in one topic summary

[Careercup] 18.1 Add Numbers two number add

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.