Saturday, May 22, 2010

Play with bits!

Q1: Write a program to print an unsigned integer that is greater than a given unsigned integer but has the same number of 1's in binary form.

Q2: If the output of the following program is 288, how many positive initial values are possible for p?

     #include <stdio.h>

     int main()

     {

        int p;

        p &= (p - 1);

        printf("%d", p);

        return 0;

    }

-- Varun

2 comments:

  1. 2) 288 = 100100000(binary)
    p = x 1 (0 0 0 ... k times )
    p-1 = x 0 (1 1 1 .. k times )

    p & (p - 1) = 100100000(in binary)

    so p could be

    100110000, 100101000, 100100100,
    100100010, 100100001

    5 possible values for p

    ReplyDelete
  2. 1) in simple terms, I would say,
    find first '01' from right in binary form and replace it with '10'.

    well, I first solved it for nos of the form p = "m 0 (1 1 1 .. k times)" in binary

    x = p + 1
    y = x&-x ( to find the last set bit )
    z = (y>>1) - 1

    ans = z|x

    Then extended this solution for numbers of the form p = "m 0 (1 1 .. k times) (0 0 .. s times) "

    w = p&-p
    x = p + w
    y = x&-x
    z = (y>>1) - w
    ans z|x

    haven't checked for trivial cases though.. should work for them too i guess.

    ReplyDelete