Determine whether an unsigned number is a power of 2.
Source: Internet
Author: User
This is an interview question. First, we can analyze the number of power forms of 2. the binary form must be 1 bits and the rest bits must be 0
Therefore, an intuitive method is to compare it with the N power of all 2, because the unsigned integer we usually consider is 32-bit, therefore, there are 32 2's N power numbers (which can be obtained by moving 1 left to 31 digits ). In the worst case, this method needs to be shifted and compared 32 times, which is less efficient.
After careful analysis, we can find that the number of N power forms of 2 is in the binary form of 0... 010... 0. If 1 is followed by I 0 (0 <= I <= 31), then this number minus 1 will show a continuous number of I 1 at the end. For example, if the binary number is 0100 and the number minus 1 equals 0011, the sum of the two numbers is 0.
Therefore, a better algorithm is: inline bool is2n (unsigned int I)
...{
If (I = 0) return false;
Else return (I & (I-1) = 0;
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.