Given an integer n, return true if it is a power of two. Otherwise, return false.An integer n is a power of two, if there exists an integer x such that n == 2x.
Question
Given an integer n, return true if it is a power of two. Otherwise, return false.An integer n is a power of two, if there exists an integer x such that n == 2x.
Solution
Here is a step-by-step solution in Python:
- First, we need to handle the special case where
nis less than or equal to 0. Since 2 to the power of any number cannot be less than or equal to 0, we returnFalsein this case.
if n <= 0:
return False
- Next, we use a bitwise trick to determine if
nis a power of two. Ifnis a power of two, thennin binary is a 1 followed by some number of 0s. Therefore,n - 1in binary is a string of 1s of the same length asn. If we take the bitwise AND ofnandn - 1, we should get 0 ifnis a power of two.
return (n & (n - 1)) == 0
So, the complete function is:
def isPowerOfTwo(n):
if n <= 0:
return False
return (n & (n - 1)) == 0
This function will return True if n is a power of two, and False otherwise.
Similar Questions
Given an integer n, return true if it is a power of three. Otherwise, return false.An integer n is a power of three, if there exists an integer x such that n == 3x.
Given a non-negative integer N, the task is to check if N is a power of 2. Print 'YES' if N is the power of 2; else, print 'NO'.
Single File Programming QuestionProblem StatementGiven a non-negative integer N, the task is to check if N is a power of 2. Print 'YES' if N is the power of 2; else, print 'NO'.Example 1Input: N = 8Output: YESExplanation: 8 is equal to 2 raised to 3 (23 = 8).Example 2Input: N = 98Output: NOExplanation: 98 cannot be obtained by any power of 2.Note: This question was asked in Adobe coding test.Input format :The input consists of an integer N, representing the non-negative integer.Output format :If N is a power of 2, the output is "YES".If N is not a power of 2, the output is "NO".Refer to the sample output for formatting specifications.Code constraints :In this scenario, the test cases fall under the following constraints:1 ≤ N ≤ 512Sample test cases :Input 1 :20Output 1 :NOInput 2 :64Output 2 :YESInput 3 :98Output 3 :NONote :The program will be evaluated only after the “Submit Code” is clicked.Extra spaces and new line characters in the program output will result in the failure of the test case.Marks :
Suppose n is an integer. Is n2 n always aninteger? Justify your answer.
If n is an even integer, then (i)n is equal to
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.