计算整数二进制中1的最大间隔是多少?

时间复杂度是O(log(N));

空间复杂度是O(1)

#include<stdio.h>

int solution(int N) {

if (N <= 0)

        return 0;

    printf(“N = %d\n”, N);

    int bitlen = 1;

    int gap = 0;

    int i;

    int temp = N;

    int x =0;

    int flag = 1;

    while (temp>>1 != 0){

        bitlen++;

        temp = temp>>1;

    }   

    for (i =0; i < bitlen; i++){

        if (N%2 == 1){

           // start count at the first bit is one

            if (flag){    

                x = i;

                flag = 0;

            }   

            if (gap < i – x -1){

                gap = i – x -1;

            }   

            x = i;

        }   

        N = N>>1;

    }   

    return gap;

}

void main (){

    printf(” 1st res = %d\n”, solution(1041));

    printf(” 2st res = %d\n”, solution(11));

    printf(” 3st res = %d\n”, solution(57));

    printf(” 4st res = %d\n”, solution(15));

}

点赞