How to check if a number is a power of 2

后端 未结 25 1922
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 03:30

Today I needed a simple algorithm for checking if a number is a power of 2.

The algorithm needs to be:

  1. Simple
  2. Correct for any ulong
25条回答
  •  耶瑟儿~
    2020-11-22 03:58

    Find if the given number is a power of 2.

    #include 
    
    int main(void)
    {
        int n,logval,powval;
        printf("Enter a number to find whether it is s power of 2\n");
        scanf("%d",&n);
        logval=log(n)/log(2);
        powval=pow(2,logval);
    
        if(powval==n)
            printf("The number is a power of 2");
        else
            printf("The number is not a power of 2");
    
        getch();
        return 0;
    }
    

提交回复
热议问题