LeetCode 1: Number of 1 Bits (C++)

代碼格式
•LeetCode不允許自己定義函數,只需要實現給定的函數即可。
•不需要定義main()函數,否則會編譯通不過。
•如果需要有輸出,直接return就行。我在第一題中使用了cout,就通不過。

題目描述

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as theHamming weight).

For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

解題思路

本題就是求一個無符號整數中1的個數,首先想到的是直接數,我的第一思路就是如此。還有一種方法就是使用技巧:n&(n-1)。

解法1:計數整數中的1。

#include<iostream>
using namespace std;
class Solution
{
    public:
        int hammingWeight(uint32_t n)
        {
            int count=0;
            for(int i=0;i<32;i++)
            {
                if (n&(1<<i)) coun0t++;//如果出現1就給計數器加一
            }
            return count;
        }
};

解法二:n&(n-1)可以將n的二進制表示的末尾1變成0,如果n末尾是0,則仍然是0.

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int count=0;
        while(n)//如果n的末尾(至少是末尾)有1則將其去掉,並計數。
        {
            n&=n-1;
            count++;
        }
        return count;
    }
};

另外:n&-n可以保留末尾的0

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