Posted on

Following are several problems that I think need exploring more.

isPowerOfTwo

This is a multiple choice problem, given a list of four answers, choose one from them. I did not think two much and only tested the options with a simple testcase. Now I find I was wrong. The right solution should be the following.

bool isPowerOfTwo2(int x)
{
    return x && !(x & (x - 1));
}

The x – 1 makes shifts the right-most 1 of the number one bit right. If x is power of 2, it should only have one 1 and with all other bits 0. In that case, all the 1’s of x(although only one) should shift 1 bit right. And the result of x & (x – 1) should be 0, since no 1 should be in the original place after -1. Now apply not to the logical expression should give us 1. And for the number that are not power of 2 except 0, it should have at least 2 bits of 1, which means (x & x – 1) will not be 0, which is the opposite of a power-of-2 number.

C++ Struct Size

I’ve written a post about it.

References

  1. https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/

Leave a Reply

Your email address will not be published. Required fields are marked *