Monday, December 19, 2011

Power of 2 or not---Power of 4 or not

Find whether a given number is a POWER of 2 or not
Also extend the above logic to find whether a number is Power of 4 or NOT

1 comment:

  1. unsigned int v;
    bool f;

    f = (v & (v - 1)) == 0;

    Note that 0 is incorrectly considered a power of 2 here. To avoid this, use:

    f = v && !(v & (v - 1));

    ReplyDelete