Here's the problem:
# 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
# of `6 % 2`, since 2 evenly divides 6 with no remainder, `6 % 2 == 0`.
My Solution
That first if statement, tells us what to reject right away -- if the number passed in isn't divisible by 2, then we know that two things: that it's definitely an odd number, and that it cannot be a power of 2.
The while loop portion was something I picked up from Codewars. Let me try to dissect and explain: The (!num) portion only, excluding the first exclamation mark, is basically saying num is false. The exclamation mark acts like negation (I think-- please feel free to correct me!). So the outer exclamation mark (!(!num)) is a double negative and is basically saying while num is true.
A while loop still needs the same components as a for-loop: the initiation (num), the condition(while num is true) and termination (num is false).
- The first if within the loop would break us out of the loop if and when num is equal to 1 (which would be our 2 to the 0 power case. If we get to this case, that means it is a power of 2 and we should return true, which the code states!
- The else if scenario checks if the remainder of num / 2 is equal to 0. If it is, divide it by 2 again.
- The last else case will handle the other cases and if the number hasn't passed the first two cases, it's not a power of two, so we should return false.
What do you think? How would you solve this problem?!
No comments :
Post a Comment