mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-26 21:58:56 +01:00
Added solution without recursion
This commit is contained in:
parent
80d52f7f6f
commit
629de26a20
1 changed files with 30 additions and 1 deletions
|
@ -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)
|
||||
|
|
Loading…
Reference in a new issue