The title is described below :

Give an integer , Write a function to determine if it is 2 To the power of .

Examples  1:
input : 1 output : true explain : 20 = 1
Examples 2:
input : 16 output : true explain : 24 = 16
Examples 3:
input : 218 output : false
Thinking analysis : This is a very simple topic , Analysis according to normal thinking , We can do it by right n  To continue to divide 2, Surplus 2 Verify is 0, If not 0 That's the case n no 2 Power of
class Solution { public: bool isPowerOfTwo(int n) { while(n>1)// judge n>1 Time Is it 2 Power of
{ if((n/2)==(n/2.0)) n=n/2; else return false; } if(n>0) judge n<=1 Is it 2 Power of return
true; else return false; } };
This method can ac however zhe' This is not the easiest way . If we've been exposed to bit operations , Then we should be able to understand j Data in a computer is represented in binary

And all of them 2 There is one thing in common that the highest bit of binary is 1, The rest are 0

So with this , There is a technical way to solve this problem
class Solution { public: bool isPowerOfTwo(int n) { if (n>0) return
((n&(n-1))==0); else return false; } };
among & Is a bitwise and operation

And why n&(n-1), Let's look at an example

hypothesis n=4, Its binary representation is 100,n-1 It means 011

Re hypothesis n=8, Its binary representation is 1000,n-1 Expressed as 0111

It's not hard to find out ,n-1 And the results of doing and computing are both 0. It can be mastered as a skill , Learn this way of thinking .

Technology
©2019-2020 Toolsou All rights reserved,
vue Changes in data Interface not updated Python realization js And Django Front and back interaction in the background JavaSwing To achieve a simple Lianliankan games C# Making a simplified version of calculator elementui Shuttle box el-transfer Display list content text too long JVM summary Regression of dependent variable order categories (R language )【C#】 The realization of student achievement information management system use css Design a simple style html login interface C language --------- Tetris ( source code )