Flip Bits
Determine the number of bits required to flip if you want to convert integer?n?to integer?m.
Have you met this question in a real interview? ? Yes ExampleGiven?n?=?31?(11111),?m?=?14?(01110), return?2.
NoteBoth?n?and?m?are 32-bit integers.
看到題目的第一想法是異或操作,c = a ^ b,然后右移求c的1的個(gè)數(shù)即為a,b不同的二進(jìn)制位數(shù),但是一提交不對(duì),為什么呢?思路是對(duì)的,只是細(xì)節(jié)沒(méi)有考慮清楚,假如a,b異號(hào),那么c必然是小于0的數(shù),然而對(duì)于一個(gè)小于0 的數(shù)執(zhí)行右移操作會(huì)進(jìn)入死循環(huán),因?yàn)閹Х?hào)的數(shù)右移會(huì)在右邊補(bǔ)充符號(hào)位,而不是0。既然這樣的話,-1右移會(huì)進(jìn)入死循環(huán);那怎么解決呢?貌似要分情況了,當(dāng)a,b同號(hào)時(shí),直接右移統(tǒng)計(jì)1的個(gè)數(shù)是沒(méi)有問(wèn)題的;當(dāng)a,b異號(hào)時(shí),則要求出c的源碼,然后統(tǒng)計(jì)源碼減1中0的個(gè)數(shù),這次不是統(tǒng)計(jì)1,而是統(tǒng)計(jì)0了。另外還有一個(gè)細(xì)節(jié)需要記住,因?yàn)樵谘a(bǔ)碼的時(shí)候,是在原碼的基礎(chǔ)上取反,然后加了一個(gè)1,那為了跟補(bǔ)碼的情況保持一致,必須講原碼減去一個(gè)1,這樣0的個(gè)數(shù)才是原補(bǔ)碼1的個(gè)數(shù),這個(gè)細(xì)節(jié)非常重要。
class Solution { public:/***@param a, b: Two integer*return: An integer*/int bitSwapRequired(int a, int b) {// write your code hereint c = a ^ b;int count = 0, tmpc = c;if (c < 0)tmpc = ~(c - 1) - 1;while (tmpc){int bit = tmpc & 0x1;count = bit ? count + 1 : count;tmpc >>= 1;}if (c < 0)return 32 - count;return count;} };總結(jié)
- 上一篇: 阿拉擦擦呀 甩葱歌 图铃
- 下一篇: 国内外概况和预测android主界面个性