Given an integer, write a function to determine if it is a power of two.

Example 1:


Input: 1
Output: true 
Explanation: 20 = 1


Example 2:


Input: 16
Output: true
Explanation: 24 = 16

Example 3:


Input: 218
Output: false

Source: leetcode | Difficulty: EASY
Tags: Bit manipulation

Mathematics

Complete search

Starter code: class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        

Solutions:
class Solution:

	def isPowerOfTwo(self, n):
		if n < 0:
			return False
		hasOne = False
		while n > 0:
			if n & 1:
				if hasOne == True:
					return False
				else:
					hasOne = True
			n = n >> 1
		return hasOne


class Solution:

	def isPowerOfTwo(self, n):
		return n > 0 and (not n & n - 1)


class Solution:

	def isPowerOfTwo(self, n):
		if n == 0:
			return False
		if n < 0:
			n **= -1
		pow_ = True
		while n and pow_:
			if n == 1:
				return True
			pow_ = not n % 2
			n //= 2
		return pow_


class Solution:

	def isPowerOfTwo(self, n):
		return True if n & n - 1 == 0 and n != 0 else False


class Solution:
	import math

	def isPowerOfTwo(self, n):
		if n < 1:
			return False
		b = str(bin(n))
		b = b.replace('0b', '')
		b = b.replace('0', '')
		return len(b) == 1


class Solution:

	def isPowerOfTwo(self, n):
		return n > 0 and 1073741824 % n == 0


class Solution:

	def isPowerOfTwo(self, n):
		return n > 0 == 2 ** 32 % n


class Solution:

	def isPowerOfTwo(self, n):
		if n < 0:
			return False
		if bin(n).replace('0b', '').count('1') == 1:
			return True
		return False