Sword-Point Solution Report (Java Edition)--No subtraction to add 47

Source: Internet
Author: User

??

Introduction

??

Generally this can not be used with the arithmetic of the problem are only to use the bit operation to do, the purpose is to strengthen everyone's understanding of computer computing, it is a bit of a nonsense

??

Solve the problem

??

First we have to think about how computers do additions, such as 3 plus 4, if the conversion to binary is 0011 and 0100, plus 7, which is 0111. , which is equivalent to two binary XOR operations

??

But let's take another example, 4 plus 4, and we'll find that the two binaries are 0100 and 0100, and the result of the XOR operation is 0000, but what we want is now, this is because the XOR operation does not take into account the problem of rounding, it seems that we have to use an operation to consider the question of rounding, remember how the carry is calculated, if the two trees on the same bit is 1, then is to carry, which is actually with the operation

??

And in the end we need to put the carry and not consider the sum of sums together, here can not be used to sum, fall, at this time we have to use the previous talk and Xor or operation, here we trickery, the sum is assigned to N1, The carry assignment to N2, to calculate, the condition of the stop is n2==0, that is, no carry

??

static int Add (int n1,int n2) {

int sum=0;

int carry=0;

do {

SUM=N1^N2;

carry= (N1&N2) <<1;

N1=sum;

N2=carry;

} while (n2!=0);

return sum;

Sword-Point Solution Report (Java Edition)--No subtraction to add 47

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.