C language - write a code to judge whether a number is 2^n power?

1. Topic Analysis

Write a code to judge whether a number is 2^n power?

If it is a normal way of thinking, we may use the pow() function and loop to remove the power of 2 to make loop judgments, but in another way of thinking, can it be easier for us to use binary digits?

For example:

010-2 binary

100 - 4 in binary

1000 - 8 in binary

………………………………

Through the above expansion, we can know that there is only one 1 in the binary of the number 2^n, so we can find the number of 1s to judge whether the number is 2^n power.

To judge whether there is only one 1, we can use the & operator to make multi-bit judgments.

Therefore, we can use the n & (n-1) method to judge. This method is to gradually lower the binary digits from right to left in a continuous cycle until they are all 0, and the binary of 2^n is There is only one 1's.

& - Nature: http://t.csdn.cn/mqp1G

n & (n-1) - the use of applications:  http://t.csdn.cn/ZzBX3

2. Code demo

int main()
{
  int n = 0;
  scanf("%d",&n);
  if ((n & (n - 1)) == 0)
  {
    printf("yesin") ;
  }
  else
  {
     printf("no\n");
  }
  return 0;
}

Guess you like

Origin blog.csdn.net/2301_76445610/article/details/132141122