2

Javascript program to find whether a number is power of two

 1 year ago
source link: https://www.geeksforgeeks.org/videos/javascript-program-to-find-whether-a-number-is-power-of-two/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Javascript program to find whether a number is power of two

Javascript program to find whether a number is power of two
  • 260 Views
  • 10/10/2022

In this video, we will write a Javascript program to Check whether a Number is a Power of 2 or not. Basically, a power of two is a number of form 2n  where n is an integer.

Examples:
=> Input: n = 37
=> Output: No

=> Input: n = 16
=> Output: Yes

=> Input:n = 12
=> Output: n= No

In the video to check whether a number is a power of 2 we use three different methods:

1. Using ceil and floor function: In this method, we use math ceil and floor functions. If the ceil and floor value of the input number is equal then the input number is the power of 2. Or we can say that If log2(n) is an integer then n is a power of 2, else not.

2. Using division operator: In this method, we keep dividing the input number by 2 iteratively and check whether n % 2 is not equal to zero and n is not equal to 1, which indicates n is not the power of 2 otherwise if n becomes 1 then it is the power of 2.

3. By checking the count of the set bits: All power of two numbers has only a one-bit set. So count the number of set bits, and if you get 1 then the number is a power of two.

For example in binary:
2 = 10
4 = 100
8 = 1000

So the time and space complexity of all the methods are as follows:

1. Using ceil and floor function
Time Complexity: O(1)
Space Complexity:(1)

2. Using division operator
Time Complexity: O(log2n)
Auxiliary Space: O(1)

3. By checking the count of set bits
Time complexity: O(N)
Auxiliary Space: O(1)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK