Solution by matugm


  • 0
    M

    First Approach

    Intuition

    Since power of four means a number obtained by multiplying 4 by itself a number of times we can try the reverse operation (divide by 4.0).

    Algorithm

    We will start with the given number & loop until it's less than 1. Then if it's exactly 1 it means that this number is a power of four.

    Otherwise it's not a power of four.

    Ruby

    def is_power_of_four(num)
      while num > 1
        num /= 4.0
      end
    
      num == 1.0
    end
    

    Notice that we need to divide by 4.0 & not just 4 for this to work.

    Complexity Analysis

    Since we keep dividing by 4 the time complexity should be O(log4 n).

    Second Approach

    Intuition

    We can use a logarithm to check if the number is a power of another.

    Algorithm

    We will use our programing language Math module to compute the logarithm & then check if it's a whole numbers (no decimal).

    Ruby

    def is_power_of_four(num)
      return false if num == 0
      return false if num < 0
    
      log = Math.log(num.abs, 4)
    
      log == log.round
    end
    

    Complexity Analysis

    Same as our first approach, but since this is implemented by programing language it will probably perform better.


  • 0
    M

    Submission for the "Write for LeetCode and get paid!" program :)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.