![]() |
VOOZH | about |
Given an array arr[] of size N, the task is to print the nearest power of 2 for each array element.
Note: If there happens to be two nearest powers of 2, consider the larger one.
Examples:
Input: arr[] = {5, 2, 7, 12}
Output: 4 2 8 16
Explanation:
The nearest power of arr[0] ( = 5) is 4.
The nearest power of arr[1] ( = 2) is 2.
The nearest power of arr[2] ( = 7) is 8.
The nearest power of arr[3] ( = 12) are 8 and 16. Print 16, as it is the largest.Input: arr[] = {31, 13, 64}
Output: 32 16 64
Approach: Follow the steps below to solve the problem:
Below is the implementation of the above approach:
4 2 8 16
Time Complexity: O(N)
Auxiliary Space: O(1)