Created
August 13, 2025 16:37
-
-
Save tatsuyax25/36c780855c9f0e088cc6af8a86f5a66f to your computer and use it in GitHub Desktop.
Given an integer n, return true if it is a power of three. Otherwise, return false. An integer n is a power of three, if there exists an integer x such that n == 3x.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number} n | |
* @return {boolean} | |
*/ | |
var isPowerOfThree = function(n) { | |
// Powers of 3 are always positive (3^0 = 1, 3^1 = 3, etc.) | |
if (n < 1) return false; | |
// Keep dividing n by 3 as long it's it's divisible | |
while (n % 3 === 0) { | |
n /= 3; // Divide n by 3 | |
} | |
// If we end up with 1, it means n was a power of 3 | |
return n === 1; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment