Knowee
Questions
Features
Study Tools

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.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Here is a step-by-step solution in Python:

  1. First, we need to handle the special case where n is less than or equal to 0. Since 2 to the power of any number cannot be less than or equal to 0, we return False in this case.
if n <= 0:
    return False
  1. Next, we use a bitwise trick to determine if n is a power of two. If n is a power of two, then n in binary is a 1 followed by some number of 0s. Therefore, n - 1 in binary is a string of 1s of the same length as n. If we take the bitwise AND of n and n - 1, we should get 0 if n is 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.

This problem has been solved

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

1/2

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.