From 629de26a201ee6563a50e651c4d7c2d511fe6048 Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Fri, 19 Mar 2021 16:19:45 -0700 Subject: [PATCH] Added solution without recursion --- data_structures/arrays/power_of_two.rb | 31 +++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/data_structures/arrays/power_of_two.rb b/data_structures/arrays/power_of_two.rb index 5ab09d6..557a402 100644 --- a/data_structures/arrays/power_of_two.rb +++ b/data_structures/arrays/power_of_two.rb @@ -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) \ No newline at end of file +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)