From fbbcdac295ac71de391d7f3881a779aba9911337 Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Fri, 19 Mar 2021 16:20:00 -0700 Subject: [PATCH] Added solution with log --- data_structures/arrays/power_of_two.rb | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/data_structures/arrays/power_of_two.rb b/data_structures/arrays/power_of_two.rb index 557a402..98edc30 100644 --- a/data_structures/arrays/power_of_two.rb +++ b/data_structures/arrays/power_of_two.rb @@ -88,3 +88,29 @@ puts is_power_of_two(n) n = 5 # Output: false puts is_power_of_two(n) + +# +# Approach 3: Using Math library +# +# Time Complexity: O(1) +# +def is_power_of_two(n) + result_exponent = Math.log(n) / Math.log(2) + result_exponent % 1 == 0 +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) \ No newline at end of file