Lintcode-a+b problem

Source: Internet
Author: User
Tags lintcode

For given numbers A and B in function Aplusb, return the sum of them.

Note

You don't need to parse the input and output. Just calculate and return.

Example

If A=1 and b=2 return 3

Challenge

Can do it with out + operation?

Clarification

is a and B both 32-bit integers?

-Yes.

Analysis:

Use bit manipulation.

Solution 1:

Caluclate every bit.

1 classSolution {2     /*3 * param a:the First integer4 * param b:the Second integer5 * return:the sum of a and B6      */7      Public intAPLUSB (intAintb) {8         intres = 0;9         intCarry = 0;Ten          for(inti=0;i<32;i++){ One             intA1 = A & 1; A             intB1 = B & 1; -             intval = 0; -             if(a1==1 && b1==1 && carry==1){ theval = 1; -Carry = 1; -}Else if((a1==1 && b1==1) | | (a1==1 && carry==1) | | (B1==1 && Carry==1) ) { -val = 0; +Carry = 1; -}Else if(a1==1 | | b1==1 | | carry==1) { +val = 1; ACarry = 0; at}Else { -val = 0; -Carry = 0; -             } -val = Val <<i; -res = Res |Val; inA = a >> 1; -b = B >> 1; to         } +  -         returnRes; the          *     } $};

Solution 2:

For a + B on any base, we can treat the plus as part:1. A + b without carry; 2. The carry generated by a +b. The a+b then equals to Part 1 plus Part 2. If Part1+part2 generates more carry, we can then repeat this procedure, until there is no carry.

1 classSolution {2     /*3 * param a:the First integer4 * param b:the Second integer5 * return:the sum of a and B6      */7      Public intAPLUSB (intAintb) {8          while(b!=0){9             intcarry = A & B;//their carry (actuall, need to move to right by one bit.TenA = A^b;//their plus result without carry. Oneb = Carry << 1; A         } -         returnA; -     } the};

Lintcode-a+b problem

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.