Home > Software engineering >  Lintcode1 B A Problem solution answer key
Lintcode1 B A Problem solution answer key

Time:09-21

[title description]

Write a function that add two Numbers a and B, You should not use + or any arithmetic operators.

Notice: There is no need to read data from standard input stream. Both the parameters are given in the function aplusb, you job is to calculate the sum and return it.

Given two integers a and b, and begged them, but you can't use + mathematical operators, such as

Note: you don't need data from the input stream to read, only need according to the two parameters of aplusb a and b, and calculate them and return line,

[title link]

http://www.lintcode.com/en/problem/a-b-problem/

[title]

Direct + there is nothing to say, the key is not + Operation: test Bit Operation, can use the bitwise ^ exclusive or two operands corresponding and carry, just need carry 1 or 0 points case discussion, strives for the better solution,

Bit operations to realize integer addition essence with binary operations, mainly with the two basic expressions: x ^ y//perform addition, regardless of carry (x& Y) & lt; <1//carry

Make x=x ^ y; Y=(x& Y) & lt; <1 iteration, each iteration carry the right operation is much a 0, most need "addend binary length" iteration is no carry, value is the result of x ^ y at this time,

[the reference answer]

http://www.jiuzhang.com/solutions/a-b-problem/
  • Related