Skip to content

Instantly share code, notes, and snippets.

@spreered
Last active September 13, 2017 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spreered/114f7d6aaaa3cd8dff4becf971e992a7 to your computer and use it in GitHub Desktop.
Save spreered/114f7d6aaaa3cd8dff4becf971e992a7 to your computer and use it in GitHub Desktop.
Power of Two
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
#使用二進位判斷
#如果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