Skip to content

Instantly share code, notes, and snippets.

@toddlers toddlers/poweroftwo.rb
Last active Dec 18, 2015

Embed
What would you like to do?
Write A Function To Determine If A Number Is A Power Of 2
def power_of_2?(number)
return false if number == 0
while(number % 2 == 0)
number = number / 2
end
return false if number > 1
true
end
def power_of_2?(number)
return true if number == 1
return false if number == 0 || number % 2 != 0
power_of_2?(number / 2)
end
def power_of_2?(number)
number != 0 && number & (number - 1) == 0
end
def power_of_two(number)
result = Math.log(number) / Math.log(2)
result - result.floor == 0
end
def test(x)
return ( x & (x -1 )) == 0
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.