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 2048<<1
int solution(int n)
{
    int i=0;
    int sf=0, ef=0; //start flag, end flag
    int count=0, group=0;
    int longest_count=0;

    for(i=RANGE;i;i>>=1)
    {
        if(sf)
        {
            if(!(i&n)) //0
                count++;
            if(i&n) //1
                ef=1;
        }
        if (ef)
        {
            ++group;
            if (count==0)
                --group;
            else
                DEB("sf=%d, ef=%d, count=%d, group=%d\n", sf, ef, count, group);
                longest_count=((longest_count)>(count)?(longest_count):(count));
            count=0;
            sf=0;
            ef=0;
        }
        if(i&n) //1
            sf=1;
    }
    
    return longest_count;
}

int main (int argc, char *argv[])
{
    int i=0, n=0;
    int ret=0;
    if(argc <2 || argc >2)
    {
        printf("Enter a positive integeer N\n");
        return -1;
    }
    sscanf(argv[1], "%d", &n);

#ifdef DEBUG_ENV
    printf("RANGE=%d\n", RANGE);
    for(i=RANGE;i;i>>=1)
        printf(i&n?"1":"0");
    printf("\n");
#endif

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

./c 553
RANGE=1024
01000101001
sf=1, ef=1, count=3, group=1
sf=1, ef=1, count=1, group=2
sf=1, ef=1, count=2, group=3
binary gap of length is:3

沒有留言:

張貼留言