Tuesday, December 9, 2014

Position of String of 1-bits in a c lang



Find the Position of String of 1-bits in a Number for a given Length

#include 
#include  
void main()
{
    int n, len, pos = 0, i = 0, count = 0;
    clrscr();
    printf("**Finding the position of 1-bits in a number for given length**\n");
    printf("enter a number\n");
    scanf("%d", &n);
    printf("enter the length\n");
    scanf("%d", &len);
    while (i <= 32)
    {
        if ((n & 1) ==  1)   
        {
            count++;
            pos = i;
            if (count ==  len)    
            {
                break;
            }
        }
        if ((n & 1) ==  0)
        {
            count = 0;
        }
        n = n>>1;
        i++;
    }
    printf("the position of 1 in the string : %d\n", pos); 
    getch();
}

Output
 
**Finding the position of 1-bits in a number for given length**
enter a number
10000
enter the length
3
the position of 1 in the string : 10
enter a number
700
enter the length
4
the position of 1 in the string : 5


No comments:

Post a Comment