最大二进制数伸展

时间:2014-08-26 18:00:15

标签: c

给出非负整数N. N的最大二进制1伸展是在N的二进制表示中设置为1的最长连续比特序列的长度。例如,考虑N = 114,067。其二进制表示为11011110110010011.其最大二进制伸展为1从上面的描述中等于4。

有人能告诉我如何在C编程中解决上述问题。

1 个答案:

答案 0 :(得分:1)

该死的简短解决方案,我可以将其纳入评论:

#include<stdio.h>
main(N,L,B)
{
    N=114067,L=B=N&1;
    while(N>>=1)B=(L=(N&1)?L+1:0)>B?L:B;
    return !printf("%d",B);
}

Live demo link.


Nah ......这太短暂了,无法理解任何事情,让我们稍微扩展一下:

#include <stdio.h>

int main()
{
    int N = 0; // input value, will be read with scanf()
    int currentLength = 0; // here we will store the current number of consecutive ones
    int bestLength = 0; // here we will store the best result

    scanf("%d", &N); // read the input value from standard input

    while (N) // as long as N is greater than 0
    {
        if (N & 1) // if the last bit is set to 1
        {
            // cool, let's increment the current sequence's length
            currentLength += 1;

            // currentLength has changed, maybe now it is better than best known solution?
            if (currentLength > bestLength)
            {
                // awesome! new best solution is found
                bestLength = currentLength;
            }
        }
        else
        {
            // we have encountered 0 while scanning bits, we must start counting the length over
            currentLength = 0;
        }

        // let's move to the next bit!
        N = N >> 1;
    }

    printf("%d", bestLength); // print out the value

    return 0;
}

One more live demo link.