Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created August 13, 2025 16:37
Show Gist options
  • Save tatsuyax25/36c780855c9f0e088cc6af8a86f5a66f to your computer and use it in GitHub Desktop.
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.
/**
* @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