-
Notifications
You must be signed in to change notification settings - Fork 40
/
PowerOfThree.js
39 lines (34 loc) · 935 Bytes
/
PowerOfThree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Source : https://leetcode.com/problems/power-of-three
// Author : Dean Shi
// Date : 2017-09-14
/***************************************************************************************
*
* Given an integer, write a function to determine if it is a power of three.
*
* Follow up:
* Could you do it without using any loop / recursion?
*
* Credits:Special thanks to @dietpepsi for adding this problem and creating all test
* cases.
*
***************************************************************************************/
/**
* Recursion
* @param {number} n
* @return {boolean}
*/
var isPowerOfThree = function(n) {
if (n === 1) return true
if (n % 3 !== 0 || n === 0) return false
return isPowerOfThree(n / 3)
};
/**
* Iteration
* @param {number} n
* @return {boolean}
*/
var isPowerOfThree = function(n) {
if (n < 1) return false
while (n % 3 === 0) n /= 3
return n === 1
};