leetcode231题 题解 翻译 C语言版 Python版

来源:互联网 发布:安卓软件编写 编辑:程序博客网 时间:2024/05/29 09:09

231. Power of Two

Given an integer, write a function to determine if it is a power of two.

231.2的幂

给定一个整数,写一个函数来判断他是不是2的幂。


思路:将其一直除2即可,如果出现余数不为0的情况,就不是2的幂,如果一直除到头了余数一直是0,则是2的幂。程序中可使用与1与运算来代替模2运算,可采用右移1位运算来代替自除2运算。


bool isPowerOfTwo(int n) {    if (n < 1) return false;    if (n == 1) return true;    while (n > 1){        if ((n & 1) != 0) return false;        n >>= 1;    }    return true;}

class Solution(object):    def isPowerOfTwo(self, n):        """        :type n: int        :rtype: bool        """        if n < 1: return False        if n == 1: return True        while n > 1:            if (n & 1) != 0: return False            n >>= 1        return True


0 0
原创粉丝点击