Нou can use bitwise operators, in conjunction with a bit of math, to find out whether an integer is a power of two.
A power of two will look like this in memory:
If you take the bitwise AND of the two values, you get 0.
In binary:
Источник: http://www.cprogramming.com/tutorial/powtwosol.html
A power of two will look like this in memory:
01000000a string of zeros, with a lone one. Now, if you subtract 1 from a power of two, you'll get, with all numbers in binary:
01000000 - 00000001 = 00111111a string of ones!
If you take the bitwise AND of the two values, you get 0.
In binary:
01000000 & 00111111 = 00000000On the other hand, if you don't have a power of two, you'll have at least one additional 1:
01000001When you subtract 1, you'll still have at least one "on" bit (with a value of 1) in the same position as before, so taking the bitwise AND of the two numbers will not result in a string of 0s:
01000001 - 00000001 = 01000000 01000000 & 01000001 = 01000000So to tell if an integer is a power of two:
int is_power(int x) { return !((x-1) & x); }Note that we have to use the logical NOT, !, instead of the bitwise complement since the bitwise complement will not negate non-zero values; it just flips bits.
Источник: http://www.cprogramming.com/tutorial/powtwosol.html
Комментариев нет:
Отправить комментарий