Skip to content

Latest commit

 

History

History
32 lines (29 loc) · 1.43 KB

1.md

File metadata and controls

32 lines (29 loc) · 1.43 KB
1. A + B Problem
Write a function that add two numbers A and B.
Example
Given a=1 and b=2 return 3.
Challenge
Of course you can just return a + b to get accepted. But Can you challenge not do it like that?(You should not use + or any arithmetic operators.)
Clarification
Are a and b both 32-bit integers?
Yes.
Can I use bit operation?
Sure you can.
Notice
There is no need to read data from standard input stream. Both parameters are given in function aplusb, you job is to calculate the sum and return it.


思路:
a ^ b 表示没有考虑进位的情况下两数的和,(a & b) << 1 就是进位。
递归会终止的原因是 (a & b) << 1 最右边会多一个 0,那么继续递归,进位最右边的 0 会慢慢增多,最后进位会变为 0,递归终止。

// 主要利用异或运算来完成 
// 异或运算有一个别名叫做:不进位加法
 // 那么a ^ b就是a和b相加之后,该进位的地方不进位的结果
// 然后下面考虑哪些地方要进位,自然是a和b里都是1的地方
 // a & b就是a和b里都是1的那些位置,a & b << 1 就是进位
 // 之后的结果。所以:a + b = (a ^ b) + (a & b << 1)
 // 令a' = a ^ b, b' = (a & b) << 1
  // 可以知道,这个过程是在模拟加法的运算过程,进位不可能
   // 一直持续,所以b最终会变为0。因此重复做上述操作就可以
 // 求得a + b的值。