1. 程式人生 > >《劍指offer》學習筆記_面試題15_二進位制中1的個數

《劍指offer》學習筆記_面試題15_二進位制中1的個數

  •     1.解法1

int NumberOf1(int n){
        int count = 0;
        unsigned int flag = 1;
        while(flag){//當flag中的1移到越界後,flag值會轉變為0
            //當n&flag不為0時,表示當前flag中1對應的位置不為0
            if(n&flag)count++;
            flag = flag<<1;
        }
        return count;
    }
  •     2.解法2

    int NumberOf1(int n){
        int count=0;
        while(n){
            count++;
            n = n&(n-1);
        }
        return count;
    }