Write a method that takes in a number and returns true if it is a power of 2. Otherwise, return false.
You may want to use the
5 % 2returns the remainder when dividing 5 by 2; therefore,
5 % 2 == 1. In the case of
6 % 2, since 2 evenly divides 6 with no remainder,
6 % 2 == 0."
def is_power_of_two?(num) if num < 1 return false end while true if num == 1 return true elsif num % 2 == 0 num = num / 2 else return false end end end
def is_power_of_two?(num) 0.upto(num) do |i| return true if 2**i == num return false if 2**i > num end end
This is a problem from a beginner's course. I'm trying to return to these problems now that I've learned some more idiomatic Ruby.
Generally, are there any advantages to the model solution? Specifically, how could I improve my solution?