![]() |
Given a positive integer, find the next power of two greater than the given number using JavaScript. Examples: Input: N = 6 Below are the approaches to finding the Next Power of Two which are as follows: Table of Content 1. Using Bit ManipulationIn this approach, we use bitwise operations to find the next power of two. We start by checking if the given number is already a power of two. If it is, we simply return the number itself. Otherwise, we iteratively left shift the number until it becomes a power of two. Each left shift effectively multiplies the number by 2, incrementing the power count. Once we’ve completed the left shifts, we return 2 raised to the power count, which gives us the next power of two. Example: Implementation of program to find the Next Power of Two using Bit Manipulation
Output Next power of two: 16 Time Complexity: O(Log n) Auxiliary Space: O(1) 2. Using Math FunctionsIn this approach, we use mathematical functions to determine the next power of two. We first calculate the logarithm base 2 of the given number, which effectively gives us the exponent of the next power of two. To ensure that we obtain the next integer value higher than this exponent, we round up the result to the nearest integer using the ceiling function. Finally, we raise 2 to this power to obtain the next power of two. Example: Implementation of program to the Next Power of Two using Math Functions
Output Next power of two: 16 Time Complexity: O(1) Auxiliary Space: O(1) 3. Using loopIn this approach we use a while loop to continuously double a number until it becomes equal to the input number. Example: Implementation of program to the Next Power of Two using while loop.
Output 16 Time Complexity: O(log n) – where n is the input number Space Complexity: O(n) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |