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的個數(shù)即為a,b不同的二進制位數(shù),但是一提交不對,為什么呢?思路是對的,只是細節(jié)沒有考慮清楚,假如a,b異號,那么c必然是小于0的數(shù),然而對于一個小于0 的數(shù)執(zhí)行右移操作會進入死循環(huán),因為帶符號的數(shù)右移會在右邊補充符號位,而不是0。既然這樣的話,-1右移會進入死循環(huán);那怎么解決呢?貌似要分情況了,當a,b同號時,直接右移統(tǒng)計1的個數(shù)是沒有問題的;當a,b異號時,則要求出c的源碼,然后統(tǒng)計源碼減1中0的個數(shù),這次不是統(tǒng)計1,而是統(tǒng)計0了。另外還有一個細節(jié)需要記住,因為在補碼的時候,是在原碼的基礎(chǔ)上取反,然后加了一個1,那為了跟補碼的情況保持一致,必須講原碼減去一個1,這樣0的個數(shù)才是原補碼1的個數(shù),這個細節(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é)
- 上一篇: 阿拉擦擦呀 甩葱歌 图铃
- 下一篇: 低轨通信卫星: 开启 6G 通信时代,带