338. Counting Bits

想到了兩種解法:

(1)參照的是10進制數轉換爲2進制數的計算過程,代碼如下:

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> counts;
        for(int i=0; i<=num; i++)
        {
            int count=0;
            int temp=i;
            do{
                count += temp%2;
                temp /= 2;
            }while(temp!=0);
            counts.push_back(count);
        }
        return counts;
    }
};
 time: 148ms
(2)移位,判斷最後那個bit是0還是1,代碼如下:

class Solution {
public:
    vector<int> countBits(int num) {
	vector<int> counts;
	for(int i=0; i<=num; i++)
	{
		int count=0;
		int temp = i;
		for(int j=1;j<8*sizeof(int);j++)
		{
			count += (0x01 & temp);
			temp = temp >> 1;
		}
		counts.push_back(count);
	}
	return counts;
  }
};

time: 152ms


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章