# [RUST Tiring Notes] Rust basic grammar data type -02

2023-01-12   ES

### directory

Hello, I am Dr. Leaf, write the most beautiful blog with heart, play the best piano!

[Difficulty: Simple]

Given an integer and write a function to determine whether it is the power of 2.

Example 1:

Input:1
Output:true

Explanation: 2 0 = 1 2^0 = 1

Example 2:

Input:16
Output:true

Explanation: 2 4 = 16 2^4 = 16

Example 3:

Input:218
Output:false

• python3 implementation method 1:
class Solution:
def isPowerOfTwo(self, n: int) -> bool:

k = 0
while True:
if 2**k == n:
return True
elif 2**k > n:
break
k += 1
return False


• python3 implementation method 2: bit operation
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (n - 1) == 0

• Solution 1:

• Solution 2:bit operation

1. Original content, reprint the source!
2. The above content is organized, and it is feasible for pro -testing. If you have any problems, please correct me, thank you ~~
3. Praise, collection, and welcome to reward, I play the piano, you listen ~~ haha!

source