For given numbers a and b in function aplusb, return the sum of them.NoteYou don't need to parse the input and output. Just calculate and return.ExampleIf a=1 and b=2 return 3ChallengeCan you do it with out + Operation?ClarificationAre a and b both 32-bit integers? - Yes.
直接+沒(méi)什么好說(shuō)的,關(guān)鍵在于不用+的操作:
考驗(yàn)Bit Operation, 可以用按位^異或兩個(gè)操作數(shù)對(duì)應(yīng)位以及carry,只是carry是1還是0需要分情況討論。求更優(yōu)的解法
1 class Solution { 2 /* 3 * param a: The first integer 4 * param b: The second integer 5 * return: The sum of a and b 6 */ 7 public int aplusb(int a, int b) { 8 // Click submit, you will get Accepted! 9 int i = 0;10 int res = 0;11 int carry = 0;12 for (; i<32; i++) {13 int aa = (a >> i) & 1;14 int bb = (b >> i) & 1;15 res |= (aa ^ bb ^ carry) << i;16 if (aa == 1 && bb == 1 || ((aa ==1 || bb == 1) && carry == 1)) {17 carry = 1;18 }19 else carry = 0;20 }21 return res;22 }23 };貼一個(gè)別人的簡(jiǎn)潔思路:
位運(yùn)算實(shí)現(xiàn)整數(shù)加法本質(zhì)就是用二進(jìn)制進(jìn)行運(yùn)算。其主要用了兩個(gè)基本表達(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)制位長(zhǎng)度”次迭代就沒(méi)有進(jìn)位了,此時(shí)x^y的值就是結(jié)果。
我們來(lái)做個(gè)3位數(shù)的加法:101+011=1000 //正常加法位運(yùn)算加法:(1) 101 ^ 011 = 110(101 & 011)<<1 = 010(2) 110 ^ 010 = 100(110 & 010)<<1 = 100(3) 100 ^ 100 = 000(100 & 100)<<1 = 1000此時(shí)進(jìn)行相加操作就沒(méi)有進(jìn)位了,即000 ^ 1000=1000即是最后結(jié)果。
1 class Solution { 2 /* 3 * param a: The first integer 4 * param b: The second integer 5 * return: The sum of a and b 6 */ 7 public int aplusb(int a, int b) { 8 while(b != 0){ 9 int carry = a & b;10 a = a ^ b;11 b = carry << 1;12 }13 return a;14 }15 }或者用Recursion寫(xiě):
1 public int aplusb(int a, int b) {2 // Click submit, you will get Accepted!3 if (b == 0) return a;4 int sum = a^b;5 int carry = (a&b)<<1;6 return aplusb(sum, carry);7 }新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注