Added solution without recursion

This commit is contained in:
Jessica Kwok 2021-03-19 16:19:45 -07:00
parent 80d52f7f6f
commit 629de26a20

View file

@ -30,6 +30,7 @@
# @param {Integer} n
# @return {Boolean}
#
# Approach 1: Recursion
#
# Time Complexity: O(1)
@ -58,4 +59,32 @@ n = 4
puts is_power_of_two(n)
n = 5
# Output: false
puts is_power_of_two(n)
puts is_power_of_two(n)
#
# Approach 2: Without recursion
#
# Time Complexity: O(n)
#
def is_power_of_two(n)
while n % 2 == 0 && n != 0
n /= 2
end
n == 1
end
n = 1
# Output: true
puts is_power_of_two(n)
n = 16
# Output: true
puts is_power_of_two(n)
n = 3
# Output: false
puts is_power_of_two(n)
n = 4
# Output: true
puts is_power_of_two(n)
n = 5
# Output: false
puts is_power_of_two(n)