iT邦幫忙

2024 iThome 鐵人賽

DAY 8
0
佛心分享-刷題不只是刷題

刷經典 LeetCode 題目系列 第 8

經典LeetCode 191. Number of 1 Bits

  • 分享至 

  • xImage
  •  

在「Number of 1 Bits」這道題目中,我們要計算一個無符號整數的二進位表示中有多少個 1。這個問題本質上是在檢查一個數字的二進位中裡面出現多少個 1

每個整數在電腦中都是以二進位的形式儲存,例如,11 的二進位表示是 1011,這裡包含了三個 1。所以我們要做的就是遍歷這個數字的每一位元,數出其中有多少個 1

解法思路

  • 要知道怎麼從10進位轉2進位
  • 學會用 std::count 來 count array 比自己寫 for 迴圈 count 快

實作:

class Solution {
public:
    int hammingWeight(int n) {
        int a[32] = {0};
        int i = 0;
        while (n > 0) {
            a[i] = n % 2;
            //a[i] = n & 1; // 也可
            n = n / 2;
            //n = n >> 1; // 也可
            i++;
        }

        //int cnt = count(a, a+32, 1); // 也可
        int cnt = 0;
        for (int j = 0; j < 32; j++) {
            if (a[j] == 1) cnt++;
        }

        return cnt;
    }
};

兩個迴圈能簡化成一個迴圈嗎?在算出是1的同時就累計cnt,優化後修改如下,

class Solution {
public:
    int hammingWeight(int n) {
        int a[32] = {0};
        int i = 0;
        int cnt = 0;
        while (n > 0) {
            a[i] = n % 2;
            n = n / 2;
            if (a[i]) cnt++;
            i++;
        }
        return cnt;
    }
};

可以不要用一個陣列儲存二進位結果嗎?優化後修改如下,

class Solution {
public:
    int hammingWeight(int n) {
        int bit = 0;
        int i = 0;
        int cnt = 0;
        while (n > 0) {
            bit = n % 2;
            if (bit) {
                cnt++;
            }
            n = n / 2;
            i++;
        }
        return cnt;
    }
};

上一篇
經典LeetCode 20. Valid Parentheses
下一篇
經典LeetCode 268. Missing Number
系列文
刷經典 LeetCode 題目12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言