国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

Lintcode: A+B problem

2019-11-14 22:51:37
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
Lintcode: A+B PRoblem
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     }


發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 邯郸县| 团风县| 余庆县| 丰原市| 阿鲁科尔沁旗| 惠来县| 吕梁市| 大同市| 顺平县| 葫芦岛市| 游戏| 临清市| 民勤县| 宁化县| 察雅县| 林甸县| 浏阳市| 扎赉特旗| 曲阜市| 阿拉善右旗| 宁海县| 福安市| 长宁县| 平原县| 嫩江县| 杨浦区| 林甸县| 乌鲁木齐县| 邻水| 邳州市| 玛多县| 永德县| 铜鼓县| 仙居县| 扶风县| 岳西县| 交口县| 隆尧县| 吴桥县| 汨罗市| 武穴市|