The task:
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
%
modulo operation.5 % 2
returns the remainder when dividing 5 by 2; therefore,5 % 2 == 1
. In the case of6 % 2
, since 2 evenly divides 6 with no remainder,6 % 2 == 0
."
Model solution:
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
My solution:
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?
is_
prefix and the?
suffix are redundant. If given a choice, I would go withpower_of_2?
. \$\endgroup\$num % 2 == 0
is the same asnum.even?
. \$\endgroup\$