231. Power of Two

    xiaoxiao2021-04-13  31

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

    题解

    判断一个数是不是2的幂,即1,2,4,8……2^30(对int范围而言)

    解法1

    循环

    class Solution { public: bool isPowerOfTwo(int n) { //不大于0的肯定不是 if(n <= 0) return false; while(n % 2 == 0) n /= 2; return n == 1; } };

    或递归

    return n > 0 && (n == 1 || (n % 2 == 0 && isPowerOfTwo(n / 2)));

    解法2

    利用位运算n&(n-1)作用:将n的二进制表示中的最低位为1的改为0

    return n > 0 && !(n & (n-1));

    解法3

    既然范围在1,2,4,8……1073741824(2^30),直接通过模运算

    return n > 0 && (1073741824 % n == 0);
    转载请注明原文地址: https://ju.6miu.com/read-668880.html

    最新回复(0)