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
Rounding off numbers to some nearest power in JavaScript
We are required to write a JavaScript function that takes in a number and returns a number that can be represented as a power of 2 which is nearest to the input number.
For example: If the input number is 145, the output should be 128 because 128 (which is 2^7) is the nearest power of 2 to 145.
Understanding Powers of 2
Powers of 2 are numbers like: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512... Each number is double the previous one.
Algorithm Approach
The algorithm works by:
- Converting negative numbers to positive (handling absolute values)
- Starting with base = 1 and doubling it until we exceed the input
- Checking if the current base or the previous base is closer to the input
Example Implementation
const num = 145;
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));
Output
128
Testing with Different Values
console.log(nearestPowerOfTwo(10)); // 8 console.log(nearestPowerOfTwo(20)); // 16 console.log(nearestPowerOfTwo(100)); // 128 console.log(nearestPowerOfTwo(200)); // 256 console.log(nearestPowerOfTwo(-50)); // 64
8 16 128 256 64
Alternative Approach Using Math.log2
const nearestPowerOfTwoAlt = 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(nearestPowerOfTwoAlt(145)); // 128
console.log(nearestPowerOfTwoAlt(100)); // 128
128 128
How It Works
The first approach uses a while loop to find powers of 2. When base , it checks if the distance from num to the current base is less than half of base. If so, the current base is closer than the next power of 2.
The alternative approach uses logarithms to directly calculate the lower and upper bounds, then returns whichever is closer.
Conclusion
Both approaches effectively find the nearest power of 2. The iterative method is more intuitive, while the logarithmic approach is more mathematically direct and efficient for large numbers.
