[leetcode]-231. Power of Two(C语言)

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

方法一:

bool isPowerOfTwo(int n) {
    if(n<0)
        return false;
    double s=log10(n)/log10(2);
    if(s-(int)s==0)
        return true;
    return false;
}

方法二:

bool isPowerOfTwo(int n) {
    int i,j;
    if(n<=0)
        return false;
    if(n==1)
        return true;
    while(n!=1)
    {
        if(n%2==0)
            n=n/2;
        else
            return false;
    }
    return true;
}

方法三:

将整数n转换为二进制形式,那么2的幂次为10,100,1000,等的形式,将转换后的二进制放在数组里,看是否每一位都是0即可(开头的1没必要存储下来)

bool isPowerOfTwo(int n) {
    int a,b,i,c=0;
    int s[100];
    if(n<=0)
        return false;
    if(n==1)
        return true;
    a=n/2;
    while(a!=0)
    {
        b=n%2;
        s[c++]=b;
        n=a;
        a=n/2;
    }
    for(i=0;i<=c-1;i++)
    {
        if(s[i]!=0)
            break;
    }
    if(i==c)
        return true;
    return false;
}

猜你喜欢

转载自blog.csdn.net/shen_zhu/article/details/79594670