leetcode-868-easy

Binary Gap
思路一: 记录 bit 为 1 的位置,保留区间最大的值

public int binaryGap(int n) {
    int idx = -1;
    int result = 0;
    int i = 0;
    while (n > 0) {

        if ((n & 1) == 1) {
            if (idx == -1) {
                idx = i;
            } else {
                result = Math.max(i - idx, result);
                idx = i;
            }
        }

        n = n >> 1;
        i++;
    }

    return result;
}
posted @ 2022-10-19 21:17  iyiluo  阅读(20)  评论(0)    收藏  举报