Power of Three - LeetCode
Given an integer n, return true if it is a power of three. Otherwise, return false . An integer n is a power of three…
Given an integer
true if it is a power of three. Otherwise, return
n is a power of three, if there exists an integer
x such that
n == 3x.
Input: n = 27
Input: n = 0
Input: n = 9
Input: n = 45
Follow up: Could you solve it without loops/recursion?
First answer in Java.
- check 0 and 1 corner case.
- recursion loop n and make sure there is no MOD exist and become 1 at the end
- can add another line to count how many times it loops
Another recursion answer using two lines:
Basically, it’s the same method but more short.
[Second- brute force Java]
Using HashSet or Array to list all the possible ture answer.
notes: Arrays.binarySearch will return the index of searching result. If no exist in the array, it will return -1.
use array as list in Hashset, and check if result n contains in hashset.
[Third- using Log10, Log3]
notes: have to put log10, instead of log. There will be minor error. And this solution is math solution.