計算一個整數,轉換成二進制,裏面有多少個1ide
解法1:右移 & 1.net
int numberof1(int i) { int count = 0; while(n) { if (n & 1) count ++; n = n >> 1; } return count; }
缺陷是:
當該數爲負數,例如0x8000000,右移不是獲得0x40000000,而是0xc0000000,由於該數自己是一個負數,因此右移以後仍要保持是負數的本質。code
解法2:數不右移,而是用1左移與該數進行相 &blog
int numberof2(int n) { int count = 0; unsigned int flag = 1; while (flag) { if (n & flag) count ++; flag = flag << 1; } return count; }
解法3:這是一種比較騷的操做,方法以下:把一個整數減去1,再和原整數作與運算,會把該數最右邊的一個1變成0,那麼一個整數的二進制中有多少個1,就能夠進行多少這樣的操做
1100 - 1 = 1011
1100
& 1011
——————
1000get
1000 - 1 = 0111
1000
& 0111
——————
0000it
int numberof3(int n) { int count = 0; while(n) { ++ count; n = n & (n - 1); } return count; }
做者:爲了這一刻-我也有拼命練習
來源:CSDN
原文:https://blog.csdn.net/shi_shi08/article/details/81047658
版權聲明:本文爲博主原創文章,轉載請附上博文連接!class