-
-
Save spreered/114f7d6aaaa3cd8dff4becf971e992a7 to your computer and use it in GitHub Desktop.
Power of Two
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_power_of_two(n) | |
return false if n<=0 | |
while n>1 | |
return false if n % 2 ==1 | |
n = n/2 | |
end | |
true | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#使用二進位判斷 | |
#如果n是2的次方 2進位表示一定為 1000....00 | |
#n-1則為0111....11 | |
# and(&) 後結果一定是0 | |
def is_power_of_two(n) | |
n > 0 && (n & (n-1) == 0) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment