1. 程式人生 > >輸入一個整數,輸出該數二進位制表示中1的個數。其中負數用補碼錶示

輸入一個整數,輸出該數二進位制表示中1的個數。其中負數用補碼錶示

思路:用位運算來做,與1,第一位保持不變,前面的置0,然後判斷,再右移

class Solution {
public:
     int  NumberOf1(int n) {
         int i = 0;
         int count = 0;
         for(i = 0;i < 32;i++)
         {
             if((n&1) == 1)
                 count++;
             n = n>>1;
         }
         return count;
     }
};