Q1. Power of Two
Given an integer n
, return true if it is a power of two. Otherwise, return false.
An integer n
is a power of two, if there exists an integer x
such that n == 2x
.
Example
Input: n = 1
Output: true
Explanation: 20 = 1
Input: n = 16
Output: true
Explanation: 24 = 16
Code
/**
* @param {number} n
* @return {boolean}
*/
var isPowerOfTwo = function(n) {
if (n < 1) return false;
if (n === 1) return true;
if (n % 2 !== 0) return false;
return isPowerOfTwo(n/2)
};
Q2. Power of Four
Given an integer n
, return true if it is a power of four. Otherwise, return false
.
An integer n
is a power of four
, if there exists an integer x
such that n == 4x
.
Example
Input: n = 16
Output: true
Input: n = 5
Output: false
Code
/**
* @param {number} n
* @return {boolean}
*/
var isPowerOfFour = function(n) {
if (n < 1) return false;
if (n === 1) return true;
if (n % 2 !== 0) return false;
return isPowerOfFour(n/4)
};
Q3. Power of Three
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
.
Example
Input: n = 27
Output: true
Explanation: 27 = 33
Input: n = 0
Output: false
Explanation: There is no x where 3x = 0.
Code
/**
* @param {number} n
* @return {boolean}
*/
var isPowerOfThree = function(n) {
if(n === 1) return true;
if(n === 0) return false
return isPowerOfThree(n/3)
};
Top comments (0)