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

2023-01-12   ES  

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 20=1


Example 2:

Input:16
Output:true

Explanation: 2 4 = 16 2^4 = 16 24=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
    在这里插入图片描述

Tencent Selected Exercise 50 questions 231. 2 power.


  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

Related Posts

java implementation of unicode and Chinese mutual conversion

Logic Sri Lanka Return (Returning to the chance of numbers) jn

Little Bai Xue Python —— Use Baidu Translation API to achieve translation function

multi -step progress bar implementation method

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

Random Posts

IDEA convenient operation and configuration

Sample downsample code

webView and JS interact all methods and use

Those Python libraries that have been underestimated, see how many have you used? Wang

IOS memory management and malloc source code interpretation