轉自https://www.cnblogs.com/AndyJee/p/4630568.html
題目:
輸入一個整數,輸出該數二進制表示中1的個數。其中負數用補碼錶示。
思路:
很明顯,這道題考察的是位運算。
1、依次將整數右移,判斷整數最後一位是否爲1(&1);
問題:如果該整數爲負數,則會陷入無限循環,爲什麼?因爲負數右移的時候,左邊補1,整數右移過程中不可能爲0,因此會陷入無限循環。
補碼的移位:
左移,無論正數負數都在右邊補0;
右移,正數在左邊補0,負數在左邊補1;
1 2 3 4 5 6 7 8 9 | int NumberOf1( int n){ int count=0; while (n){ if (n&1) count++; n=n>>1; } return count; } |
2、依次將1左移i位,然後跟該整數做與&操作,如果結果不爲0,則第i位爲1;
問題:整數有多少位,就得循環多少次。
3、利用小技巧
x&(x-1)可以將整數最右邊的1變成0,通過這個小技巧,我們只要循環判斷n=n&(n-1)是否爲0,即可統計1的個數。
整數中有多少個1,則循環多少次。
4、位運算相關題目
- 用一條語句判斷一個整數是不是2的整數次方。
if(n&(n-1)==0) return true;
- 輸入兩個整數m,n,計算需要改變m的二進制表示中的多少位才能得到n?
int x=m^n; return NumberOf1(x);
代碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <iostream> using namespace std; int NumberOf1_shift( int n){ int count=0; unsigned int flag=1; while (flag){ if (n&flag) count++; flag=flag<<1; } return count; } int NumberOf1_fast( int n){ int count=0; while (n){ count++; n=n&(n-1); } return count; } int main() { cout <<NumberOf1_shift(-8)<< endl; cout <<NumberOf1_fast(-8)<< endl; return 0; } |
在線測試OJ:
http://www.nowcoder.com/books/coding-interviews/8ee967e43c2c4ec193b040ea7fbb10b8?rp=1
AC代碼:
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public : int NumberOf1( int n) { int count=0; while (n){ count++; n=n&(n-1); } return count; } }; |