Lintcode1 A+B Problem solution 题解

【题目描述】

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 parameters are given in function aplusb, you job is to calculate the sum and return it.

给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。

注意:你不需要从输入流读入数据,只需要根据aplusb的两个参数a和b,计算他们的和并返回就行。

【题目链接】

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

【题目解析】

直接+没什么好说的,关键在于不用+的操作:考验Bit Operation, 可以用按位^异或两个操作数对应位以及carry,只是carry是1还是0需要分情况讨论。求更优的解法。

位运算实现整数加法本质就是用二进制进行运算。其主要用了两个基本表达式:x^y //执行加法,不考虑进位。(x&y)<<1 //进位操作

令x=x^y ;y=(x&y)<<1 进行迭代,每迭代一次进位操作右面就多一位0,最多需要“加数二进制位长度”次迭代就没有进位了,此时x^y的值就是结果。

【参考答案】

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章