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?
Credits:Special thanks to @yukuairoy for adding this PRoblem and creating all test cases.
Subscribe to see which companies asked this question.
題目要求判斷是不是4的冪??梢岳门袛嗍欠袷?的冪的方法。
如果一個整數num是2的冪,則num&(num-1)==0,2的冪自然是4的冪,只需要再添加一個條件,即:二進制的num中0的個數是偶數個即可。
代碼:
return num&(num-1)==0 and len(str(bin(num)[3:]))%2==0
新聞熱點
疑難解答