Lintcode数字与二进制运算

1、判断某个数是否是2的幂次方

思路:如果n是2的指数次方,那么他的二进制必然只有第一位为1,而刚好n-1就全为1,且比n少一位,所以只要与运算为0即可。
class Solution:
    """
    @param n: An integer
    @return: True or false
    """
    def checkPowerOf2(self, n):
        # write your code here
        return (n & (n - 1) == 0 and n!=0)

2、尾部的0

思路:将所有因子分解为质数,我们可以知道,产生一个0,必然只要一个5乘以一个2,所以只要统计5的个数即可。
class Solution:
    """
    @param: n: An integer
    @return: An integer, denote the number of trailing zeros in n!
    """
    def trailingZeros(self, n):
        # write your code here, try to do it without arithmetic operators.
        sum = 0
        while n > 0:
            sum += n //5
            n //= 5
        return sum

posted on 2018-10-30 08:35  哟,写bug呢??  阅读(131)  评论(0编辑  收藏  举报

导航