342. Power of Four

problem

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.

求一个数是不是4的幂
进阶要求不用循环递归

  • 转换为二进制,转为字符串,正则判断

solution

注意0和负数

import re
class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num == 1:
            return True
        numStr = str(bin(num))
        regex = re.compile(r"^0b1(00)+$")
        if regex.findall(numStr):
            return True
        return False
  • 如果把-4的幂也加进来,暂时没想到正则怎么写,分开写的
class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num == 1:
            return True
        numStr = str(bin(num))
        if num > 0 :
            regex = re.compile(r"^0b1(00)+$")
            if regex.findall(numStr):
                return True
        else:
            regex = re.compile(r"^-0b1((00)+){2}00$")
            if regex.findall(numStr):
                return True
        return False

discuss 1

联合起来都是先判断是否2的幂,然后判断是否4的幂

  • 对于数学特性应用的更深
import re
class Solution(object):
    def isPowerOfFour(self, num):
        return num > 0 and num &(num-1) == 0 and (num-1) % 3 == 0
  • num & (num -1) 当两边都是数字时,&表示按位与
  • (num-1) % 3 为什么一定是0,因为其中一个4-1=3
  • 反过来联合起来如何能确认就一定是4的幂而不是其他什么数?
  1. 满足num & (num -1)==0 ,则num一定是2的幂
  2. 2的幂分为两种2(2k+1) , 2(2k) (后者其实就是4的幂)
  3. 2(2k+1) -1 % 3 不会等于0 ; 因为2(2k+1)=2(2k)*2 ,可以推导出2(2k+1) -2 % 3 才是 0

First, Any number passes "n^(n-1)== 0 " must be powers of 2.
Second, all numbers above could be further categorized to 2 class. A: all numbers that are 2^(2k+1) and B: all numbers that 2^(2k).
Third, we could show that 2^(2k+1)-1 could not pass the test of (n-1)%3==0. (by induction) So all A are ruled out, leaving only B, which is power of 4.

Since 2^{2k+1}-1 = 2x(2^{2k} - 1) + 1 and 2x(2^{2k} - 1) % 3 == 0, (2^{2k+1}-1) % 3 = (2x(2^{2k} - 1) + 1) % 3 == 1.

discuss 2

def isPowerOfFour(self, num):
        return num != 0 and num &(num-1) == 0 and num & 0x55555555== num
  • num & 0x55555555== num

这个比较好理解,2的幂有两种一种也是4的幂2(2k),二进制1位于奇数位上;另一种2(2k+1),二进制1位于偶数位上

posted @ 2016-10-15 15:38  Salmd  阅读(88)  评论(0)    收藏  举报