💡
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 Two (231)

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

PreviousPower of Three (326)NextCount Prime (204)

Last updated 4 years ago

Was this helpful?

Approach 1:

We check if n can be divided by 2. If yes, divide n by 2 and check it repeatedly.

**Could also implement it recursively however less eficient due to space being used in the call stack

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

Complexity: O(log(N)time

Approach2 :

Very intuitive using bitcount. If n is the power of 2, the bit count of n is 1. Note that 0b1000...000 is -2147483648, which is not the power of two, but the bit count is 1.

return n > 0 && Integer.bitCount(n) == 1;

Time complexity = O(1) The time complexity of bitCount() can be done by a fixed number of operations. More info in .

https://stackoverflow.com/questions/109023