💡
Seb's Whiteboard
  • 👨‍💻Welcome, I'm Sebastien St Vil
  • Extras
    • Gradient Descent
    • How I learned Java
    • Machine Learning by Andrew Ng
  • Projects
    • 📉Backtest Equity Trading with SMA Strategy
    • Wellington GA Lab
    • Stock analysis
    • 📈Time Series Regression-based Trading Strategy
  • Arrays & Strings
    • Best Time to Buy and Sell Stock II
    • Online Stock Span
    • Implement strStr()
    • 2Sum
    • 3Sum
    • 3Sum Closest
    • 4Sum II
    • Set Matrix Zeroes
    • Group Anagrams
    • Longest Substring Without Repeating Characters
    • Remove Duplicates from Sorted Array
    • Move Zeroes
    • Valid Sudoku
    • Rotate Image
    • First Unique Character in a String
    • Design a Circular Queue
    • Longest Common Prefix
  • Binary Tree
  • Second Minimum Node In a Binary Tree (671)
  • Design
  • LRU Cache
  • Min Stack (155)
  • Sorting & Searching
    • Merge Sorted Array (88)
    • First Bad Version
  • Math
    • Power of Three (326)
    • Power of Two (231)
    • Count Prime (204)
    • Roman to Integer (13)
    • Fizz Buzz (412)
    • Count-and-Say
  • Dynamic Programming
    • Pascal's Triangle (118)
  • Linked List
    • Copy List with Random Pointer
    • Remove Nth Node From End of List
    • Remove Duplicated from Sorted List II
  • Tips
    • Finding dups
  • Sliding Window
    • Subarray Product Less Than K
Powered by GitBook
On this page

Was this helpful?

  1. Math

Power of Three (326)

Given an integer, write a function to determine if it is a power of three.

Approach 1:

the simplest way to find if a number n is a power of c is simply by continually dividing n by c as long as the remainder is 0.

class Solution {
    public boolean isPowerOfThree(int n) {
        if(n < 1) return false;
        while(n % 3 == 0) 
            n/= 3;
        return n == 1;
    }
}

Complexity: O(log2(N) time

Approach2 :

We can solve this one just by using math. if n = 3^x, then x = log(n) / log(3), and thus we come to the solution.

Here is the math:

log(n) / log(3) <==> log(3)^x / log(3) for n == 3 ^ x, and x is integer. Use log formula to bring x to front, we have x*log(3) / log(3), which is equal to x. We only need to check if x is an whole number by using x % 1 == 0.

class Solution {
    public boolean isPowerOfThree(int n) {
        double x = Math.log10(n) / Math.log10(3);
        return x % 1 == 0;
    }
    //log10 is used to avoid a precision erro from using log2
}

Complexity: O(N) time and O(1) space.

PreviousFirst Bad VersionNextPower of Two (231)

Last updated 4 years ago

Was this helpful?