[LeetCode][JavaScript]Power of Four
Power of Four
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
求一个数是不是4的N次幂,要求不能用循环和递归。
位运算,转成二进制后,很容易发现都是100的N次幂。
把二进制的结果直接看做十进制,求100为底的log,如果结果是整数返回true。
1 /** 2 * @param {number} num 3 * @return {boolean} 4 */ 5 var isPowerOfFour = function(num) { 6 if(num <= 0) return false; 7 num = parseInt(num.toString(2), 10); 8 var log100 = Math.log(num) / Math.log(100); 9 return Math.abs(Math.round(log100) - log100) < 1e-10 ? true : false; 10 };