Given a positive integer N, the task is to find the minimum absolute difference between N and any power of 2.
Input: N = 3
Smaller power of 2 nearest to 3 is 2, abs(3 – 2) = 1
Higher power of 2 nearest to 3 is 4, abs(4 – 3) = 1
Input: N = 6
- Find the highest power of 2 less than or equal to N and store it in a variable low.
- Find the smallest power of 2 greater than or equal to N and store it in a variable high.
- Now, the answer will be max(N – low, high – N).
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Program to find whether a no is power of two
- Power Set
- Minimum number of jumps to reach end
- Find minimum number to be divided to make a number a perfect square
- Find whether a given number is a power of 4 or not
- Write you own Power without using multiplication(*) and division(/) operators
- Check if a number can be expressed as x^y (x raised to power y)
- Find minimum number of coins that make a given value
- Minimum number of squares whose sum equals to given number n
- Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
- Modular Exponentiation (Power in Modular Arithmetic)
- Count minimum steps to get the given desired array
- Check if a number is a power of another number
- Find minimum number of merge operations to make an array palindrome
- Find the minimum difference between Shifted tables of two numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.