- 2021-01-03 13:39
*views 3*- Python
- Learn-Python

<> Xiao Ming asked me a question ：

<> How to use it python Judge whether a number is 2 Of n To the power of ?

<>Sample Input：

2

<>Sample Output

True

<> My code is as follows ：

n = int(input()) if n & (n - 1) == 0: print('True') else: print('False')

<> My thoughts

*

Seeing this problem, the first thing I think of is to do it in a circle , Should be able to do it , However, if the number is large, it is estimated that the memory will overflow .

*

switching sites , Change a few rules

for i in range(0, 10): print(bin(2 ** i)) result ： 0b1 0b10 0b100 0b1000 0b10000

0b100000 0b1000000 0b10000000 0b100000000 0b1000000000

It's obvious , If a number is 2 Of n Power , Then convert the number to binary and then to string, and there is only one of them 1. So I found this way :

n = str(bin(n)) if n.count('1') == 1: print(' What's the number 2 Of n Power ')

however , If it's just like this, the robustness is too poor from the perspective of programming

We can have an in-depth observation ：

for i in range(0, 10): print(bin(2 ** i - 1)) result ： 0b0 0b1 0b11 0b111 0b1111

0b11111 0b111111 0b1111111 0b11111111 0b111111111

Get the law ： If it's a number i by 2 Of n Power , be i&(i-1)=0.

notes ：& ： Bitwise and operators ： Two values involved in the operation , If both corresponding bits are 1, The result of this bit is 1, Otherwise 0.

Of course, we need to do some judgment and exception handling , But here's how , You don't have to care about the details .

<> Learning experience

An interesting example of a combination of operators and judgments , A review of binary computing . The joy of solving problems feels good , keep trying , There will always be growth, won't there ?

<> come on. !!!

<> You can do that ! You always believe in yourself like this !

Technology

- Python146 blogs
- Java131 blogs
- Vue86 blogs
- Flow Chart79 blogs
- javascript42 blogs
- C++41 blogs
- programing language38 blogs
- MySQL37 blogs
- more...

Daily Recommendation

©2020-2021 ioDraw All rights reserved

2020 The 11th National Blue Bridge Cup C/C++B Group summary Python Making confession applet —— From code to packaging exe“ Little monk's game ”- - Hanoi be based on 51 Eight way responder of single chip microcomputer Proteus Simulation design use python Generate non duplicate string combinations BN layer pytorch realization 20210601-C++ interview [ Thesis reading ]HRNetV1,HRNetV2,HRNetV2p Blockchain journey ( three ) Smart contract and consensus mechanism A letter from a mechanical and electrical student to himself ten years later