2017年10月21日 星期六

Lesson1

Codility - 1: Lesson1
BinaryGap Find longest sequence of zeros in binary representation of an integer.
#include <stdio.h>
#include <stdlib.h>

//#define DEBUG_ENV
#ifdef DEBUG_ENV
#define DEB(fmt,args...) printf(fmt ,##args)
#else
#define DEB(fmt,args...)
#endif

#define RANGE 24<<1
int solution(int N)
{
    int i=0, j=0;
    int b=0, bn=0;
    int c1=0, c2=0, c3=0; 
    for(i=j=RANGE; i; i>>=1)
    {
        b=i&N?1:0;
        j>>=1;
        bn=j&N?1:0;

        if( (b==1 && bn==0) )
        {
            c1++;
        }
        if ( b==0 )
        {
            if (c1 > 0)
                c2++;
        }
        if ( b==0 && bn==1 )
        {
            DEB("c2=%d, c3=%d\n", c2, c3);
            if (c3 < c2)    
                c3=c2;
            c2=0;
        }
        DEB("b=%d, bn=%d, i=%d, c1=%d, c2=%d, c3=%d\n", b, bn, i, c1, c2, c3);
    }   
    return c3; 
}

int main (int argc, char *argv[])
{
    int i=0, j=0, n=0, b=0, bn=0;
    unsigned long int range=pow(2,16);
    int ret=0;
    int c1=0, c2=0, c3=0;
    if(argc <2 || argc >2)
    {
        printf("Enter a positive integeer N\n");
        return -1;
    }
    sscanf(argv[1], "%d", &n);

    for(i=RANGE;i;i>>=1)
        printf(i&n?"1":"0");
    printf("\n");

    ret=solution(n);
    printf("binary gap of length is:%d\n", ret);
    return 0;
}

沒有留言:

張貼留言