Max Binary Gap(Codality)

问题:Get maximum binary Gap.

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation1000010001) and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.

public int maxBinGap(int num) {
    int max = 0;
    int count = -1;
    int digit = 0;

    while (num > 0) {
        //get right most bit & shift right
        digit = num & 1;
        num = num >> 1;

        if (digit == 0 && count >= 0) {
            count++;
        }

        if (digit == 1) {//(重新)开始计算gap
            max = count > max ? count : max;
            count = 0;
        }
    }

    return max;
}

results matching ""

    No results matching ""