当前位置:网站首页>Power of leetcode-231-2

Power of leetcode-231-2

2022-07-07 16:11:00 _ Spring_

Title Description

Given an integer , Write a function to determine if it is 2 Power square .
examples

Their thinking

Determine whether an integer is 2 Power square , You can use 2 Properties of the power of , Turn numbers into binary .
We know , If a number n yes 2 Power square , Then its binary representation must first be 1, The rest are 0. and n-1 In the binary representation of , The first became 0, The rest are 1.
for example , The figure below represents n=16 Binary representation of time :

…… 2 4 2^{4} 24 2 3 2^{3} 23 2 2 2^{2} 22 2 1 2^{1} 21 2 0 2^{0} 20
n=1610000
n=1501111

& The characteristic of operation is , Same as 1, Different for 0
In this case ,n and n-1 Do and calculate (&), Everyone is 0&1, The result must be 0
That is to say if n yes 2 Power square , be n&(n-1)=0
If n No 2 Power square , The result is greater than 0
therefore , utilize & To judge by operation

Code

Code 1 : Forward calculation
Stick me first 2min Code completed within (laji code

import math
def isPowerOfTwo(self, n):
    p = 0
    if n <= 0:
        return False
    while True:
        num = math.pow(2, p)     
            
        if n < num:
            return False
        elif n == num:
            return True
        else:
            p += 1
            continue

Code 2 : Reverse calculation

def isPowerOfTwo(self, n):
    if n:
        while n % 2 == 0 :
            n /= 2
        return n == 1
    return False

Code one is as efficient as code two ( As low as )

Code three : Someone else's code

def isPowerOfTwo(self, n):
    if n < 1:
        return False
    return not (n & (n-1))

Simple and clear , Efficient and comfortable .

原网站

版权声明
本文为[_ Spring_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071353002507.html