Skip to content

E868.二进制间距

bit manipulation, https://leetcode.cn/problems/binary-gap/

cpp
#include <iostream>
#include <vector>
using namespace std;

class Solution
{
public:
    int binaryGap(int n)
    {
        int last = -1, ans = 0;
        for (int i = 0; n; ++i)
        {
            if (n & 1)
            {
                if (last != -1)
                    ans = max(ans, i - last);
                last = i;
            }
            n >>= 1;
        }

        return ans;
    }
};

int main()
{
    cin.tie(nullptr)->sync_with_stdio(false);

    Solution sol;
    cout << sol.binaryGap(22) << '\n';
    return 0;
}

共用时5min

简单的位运算

cpp
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    int binaryGap(int n) {
        int ans = 0, prev = -1, pos = 0;
        while (n) {
            if (n & 1) {
                if (prev != -1) ans = max(ans, pos - prev);
                prev = pos;
            }
            n >>= 1;
            pos++;
        }
        return ans;
    }
};

用时5min