【題目描述】
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.
給出兩個整數(shù)a和b, 求他們的和, 但不能使用 + 等數(shù)學(xué)運(yùn)算符。
注意:你不需要從輸入流讀入數(shù)據(jù),只需要根據(jù)aplusb的兩個參數(shù)a和b,計(jì)算他們的和并返回就行。
【題目鏈接】
http://www.lintcode.com/en/problem/a-b-problem/
【題目解析】
直接+沒什么好說的,關(guān)鍵在于不用+的操作:考驗(yàn)Bit Operation, 可以用按位^異或兩個操作數(shù)對應(yīng)位以及carry,只是carry是1還是0需要分情況討論。求更優(yōu)的解法。
位運(yùn)算實(shí)現(xiàn)整數(shù)加法本質(zhì)就是用二進(jìn)制進(jìn)行運(yùn)算。其主要用了兩個基本表達(dá)式:x^y //執(zhí)行加法,不考慮進(jìn)位。(x&y)<<1 //進(jìn)位操作
令x=x^y ;y=(x&y)<<1 進(jìn)行迭代,每迭代一次進(jìn)位操作右面就多一位0,最多需要“加數(shù)二進(jìn)制位長度”次迭代就沒有進(jìn)位了,此時x^y的值就是結(jié)果。
【參考答案】