[LeetCode] 868. Binary Gap 二進制間隙



Given a positive integer `N`, find and return the longest distance between two consecutive 1's in the binary representation of `N`.

If there aren't two consecutive 1's, return 0.

Example 1:

Input: 22
Output: 2
Explanation:
22 in binary is 0b10110.
In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
The first consecutive pair of 1's have distance 2.
The second consecutive pair of 1's have distance 1.
The answer is the largest of these two distances, which is 2.

Example 2:

Input: 5
Output: 2
Explanation:
5 in binary is 0b101.

Example 3:

Input: 6
Output: 1
Explanation:
6 in binary is 0b110.

Example 4:

Input: 8
Output: 0
Explanation:
8 in binary is 0b1000.
There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.

Note:

  • 1 <= N <= 10^9

這道題給了我們一個正整數,問其二進制表示數中兩個 '1' 之間的最大距離是多少。比如整數 22 的二進制為 10110,那么可以看出前兩個 '1' 之間的距離最大,所以返回2即可。其實這道題的考察點就是如何按位取數,對一個二進制數直接與 '1',就可以提取出最低位,然后和0比較大小,就知道最低位是0還是1了。當然為了每一位的是0還是1,一般有兩種處理方法,一種是直接將原數字右移一位,則之前的最低位被移除了,再和 '1' 相與即可,直到原數字變為0停止。另一種方法是直接右移固定的位數再與 '1',因為整型數只有 32 位,所以可以直接取出任意位上的數字。那么既然要求兩個 '1' 之間的最大距離,那么只要關心 '1' 的位置即可,一種比較直接的思路就是先遍歷一遍各位上的數字,將所有 '1' 的坐標位置都保存到一個數組 pos 之中,然后再遍歷這個 pos 數組,計算相鄰兩個數字的差,即兩個 '1' 之間的距離,更新結果 res 即可得到最大距離,參見代碼如下:
解法一:
class Solution {
public:
    int binaryGap(int N) {
        vector<int> pos;
        for (int i = 0; i < 32; ++i) {
            if (((N >> i) & 1) != 0) pos.push_back(i);
        }
        int res = 0, n = pos.size();
        for (int i = 1; i < n; ++i) {
            res = max(res, pos[i] - pos[i - 1]);
        }
        return res;
    }
};

我們也可以只用一個循環來完成,而且不用 pos 數組,只用一個變量 last 來記錄上一個遍歷到的 '1' 的位置,初始化為 -1。那么在遍歷的過程中,若遇到了 '1',則判斷 last 是否大於等於0,是的話則表示之前已經遇到了 '1',那么當前位置i減去 last,即為兩個 '1' 之間的距離,用來更新結果 res,然后再更新 last 為當前位置i,繼續遍歷即可,參見代碼如下:
解法二:
class Solution {
public:
    int binaryGap(int N) {
        int res = 0, last = -1;
        for (int i = 0; i < 32; ++i) {
            if (((N >> i) & 1) != 0) {
                if (last >= 0) res = max(res, i - last);
                last = i;
            }
        }
        return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/868


參考資料:

https://leetcode.com/problems/binary-gap/

https://leetcode.com/problems/binary-gap/discuss/149945/Simple-Java-(10-ms)

https://leetcode.com/problems/binary-gap/discuss/149835/C%2B%2BJavaPython-Dividing-by-2


[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM