Knowee
Questions
Features
Study Tools

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'.

Question

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'.

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

Solution

Sure, here is a step-by-step solution to check if a given non-negative integer N is a power of 2:

  1. First, we need to understand that a number is a power of 2 if it's binary representation has only one '1' and the rest of the digits are '0'. For example, 2 (10 in binary), 4 (100 in binary), 8 (1000 in binary) and so on.

  2. So, to check if a number is a power of 2, we can use bitwise operations. Bitwise operations are operations that directly manipulate the bits of binary numbers.

  3. The bitwise AND operation (&) can be used to check if a number is a power of 2. The operation N & (N - 1) will be zero if N is a power of 2.

  4. Here is the step-by-step process:

    • Subtract 1 from the number N. Let's call this result M. So, M = N - 1.
    • Perform a bitwise AND operation on N and M. Let's call this result P. So, P = N & M.
    • If P is 0, then N is a power of 2. If P is not 0, then N is not a power of 2.
  5. Here is a Python code snippet that implements the above steps:

def is_power_of_two(N):
    if N == 0:
        return 'NO'
    else:
        return 'YES' if (N & (N - 1)) == 0 else 'NO'

This function takes an integer N as input and returns 'YES' if N is a power of 2, and 'NO' otherwise.

This problem has been solved

Similar Questions

def print_n(s, n):     if n > 0:          print(s)          print_n(s, n-1)     return nn = 3while print_n("hi", n):     print_n("there!", n)     n = 0

What is the output? x = True y = False z = False if x or y and z: print("yes") else: print("no")

Write a Python class to implement pow(x, n).*please upload screenshot of output also.

Write an HTML and JavaScript program which accepts N as input and print N is oddor even number

From the below code which one is valid x=2,3,4,5print(x)Yes, 2 is printedYes, [2,3,4,5] is printedNo, too many values to unpackYes. (2,3,4,5) is printed

1/1

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.