📜  C程序,查找“否”是否为2的幂

📅  最后修改于: 2021-05-28 03:28:01             🧑  作者: Mango

给定一个正整数,编写一个函数以查找是否为2的幂。

例子 :

Input : n = 4
Output : Yes
22 = 4

Input : n = 7
Output : No

Input : n = 32
Output : Yes
25 = 32

1.一种简单的方法是简单地以2为底的数字取对数,如果得到整数,则数字为2的幂。

C
// C Program to find whether a
// no is power of two
#include 
#include 
#include 
  
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
    return (ceil(log2(n)) == floor(log2(n)));
}
  
// Driver program
int main()
{
    isPowerOfTwo(31) ? printf("Yes\n") : printf("No\n");
    isPowerOfTwo(64) ? printf("Yes\n") : printf("No\n");
    return 0;
}
  
// This code is contributed by bibhudhendra


C
#include 
#include 
  
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
    if (n == 0)
        return 0;
    while (n != 1) {
        if (n % 2 != 0)
            return 0;
        n = n / 2;
    }
    return 1;
}
  
/*Driver program to test above function*/
int main()
{
    isPowerOfTwo(31) ? printf("Yes\n") : printf("No\n");
    isPowerOfTwo(64) ? printf("Yes\n") : printf("No\n");
    return 0;
}


C
#include 
#define bool int
  
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int x)
{
    /* First x in the below expression is for the case when x is 0 */
    return x && (!(x & (x - 1)));
}
  
/*Driver program to test above function*/
int main()
{
    isPowerOfTwo(31) ? printf("Yes\n") : printf("No\n");
    isPowerOfTwo(64) ? printf("Yes\n") : printf("No\n");
    return 0;
}


输出:
No
Yes

2.另一个解决方案是将数字除以二,即迭代地做n = n / 2。在任何迭代中,如果n%2变为非零且n不为1,则n不是2的幂。如果n为1,则为2的幂。

C

#include 
#include 
  
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int n)
{
    if (n == 0)
        return 0;
    while (n != 1) {
        if (n % 2 != 0)
            return 0;
        n = n / 2;
    }
    return 1;
}
  
/*Driver program to test above function*/
int main()
{
    isPowerOfTwo(31) ? printf("Yes\n") : printf("No\n");
    isPowerOfTwo(64) ? printf("Yes\n") : printf("No\n");
    return 0;
}
输出:
No
Yes

3.两个数字的所有幂仅设置一位。所以算一下。设置位,如果得到1,则数字为2的幂。请参阅以整数对设置位进行计数以对设置位进行计数。

4.如果我们将2的幂乘以1,则唯一的置1位之后的所有未置1位置1;并且置位变为未置位。

例如对于4(100)和16(10000),我们减去1后得到
3 –> 011
15 –> 01111

因此,如果数字n为2的幂,则n与n-1的按位与&将为零。我们可以说n是2的幂或不是基于n&(n-1)的值。当n为0时,表达式n&(n-1)将不起作用。为了处理这种情况,我们的表达式也将变为n&(!n&(n-1))(感谢https://www.geeksforgeeks.org/program -查找是否有二的力量/穆罕默德(Mohammad)添加此案例)。
下面是此方法的实现。

C

#include 
#define bool int
  
/* Function to check if x is power of 2*/
bool isPowerOfTwo(int x)
{
    /* First x in the below expression is for the case when x is 0 */
    return x && (!(x & (x - 1)));
}
  
/*Driver program to test above function*/
int main()
{
    isPowerOfTwo(31) ? printf("Yes\n") : printf("No\n");
    isPowerOfTwo(64) ? printf("Yes\n") : printf("No\n");
    return 0;
}
输出:
No
Yes

请参阅程序上的完整文章,以了解否是否为2的幂以获取更多详细信息!

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。