Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Nearest power 2 of a number - JavaScript
We need to write a JavaScript function that takes a number and returns the nearest power of 2. A power of 2 is any number that can be expressed as 2n where n is a whole number (1, 2, 4, 8, 16, 32, 64, 128, 256, etc.).
For example, if the input is 365, the output should be 256 because 256 (28) is closer to 365 than the next power of 2, which is 512 (29).
Algorithm Explanation
The algorithm works by:
- Starting with base = 1 (20)
- Doubling the base until it exceeds the input number
- Checking if the current base is closer than the next power of 2
- Returning the nearest power of 2
Example
const num = 365;
const nearestPowerOfTwo = num => {
// dealing only with non-negative numbers
if(num < 0){
num *= -1;
}
let base = 1;
while(base < num){
if(num - base < Math.floor(base / 2)){
return base;
};
base *= 2;
};
return base;
};
console.log(nearestPowerOfTwo(num));
console.log(nearestPowerOfTwo(10)); // Testing with 10
console.log(nearestPowerOfTwo(100)); // Testing with 100
256 8 128
How It Works
Let's trace through the example with input 365:
- base = 1: 365 - 1 = 364, which is ? 0.5, so continue
- base = 2: 365 - 2 = 363, which is ? 1, so continue
- base = 4: 365 - 4 = 361, which is ? 2, so continue
- Continue until base = 256: 365 - 256 = 109, which is < 128, so return 256
Alternative Approach Using Math Functions
Here's a more concise solution using logarithms:
const nearestPowerOfTwoMath = num => {
if(num <= 0) return 1;
const lower = Math.pow(2, Math.floor(Math.log2(num)));
const upper = Math.pow(2, Math.ceil(Math.log2(num)));
return (num - lower <= upper - num) ? lower : upper;
};
console.log(nearestPowerOfTwoMath(365)); // 256
console.log(nearestPowerOfTwoMath(10)); // 8
console.log(nearestPowerOfTwoMath(17)); // 16
256 8 16
Comparison
| Method | Time Complexity | Readability |
|---|---|---|
| Loop-based | O(log n) | More intuitive |
| Math functions | O(1) | More concise |
Conclusion
Both approaches find the nearest power of 2 effectively. The loop-based method is more intuitive to understand, while the math-based approach is more efficient and concise.
Advertisements
