Determine if num is a power of two in java? [duplicate]

风格不统一 提交于 2019-12-09 23:20:06

问题


Possible Duplicate:
How to check if a number is a power of 2

How could I write a method that would return true if passed in the value 2, 4, 8, 32, 64, and so on?


回答1:


This is probably the best way:

((value & -value) == value)



回答2:


Might want to look at this if you need a fast algorithm:

http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two



来源:https://stackoverflow.com/questions/9146855/determine-if-num-is-a-power-of-two-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!