Given an integer x. The task is to convert x to the form 2n – 1 by performing the following operations in specified order on x:
- You can select any non-negative integer n and update x = x xor (2n – 1)
- Replace x with x + 1.
The first applied operation must be of first type, the second of second type, the third again of first type and so on. Formally, if we number the operations from one in the order they are executed, then odd-numbered operations must be of the first type and the even-numbered operations must be of second type. The task is to find the number of operation required to convert x to the form 2n – 1.
Input: x = 39
Operation 1: Pick n = 5, x is transformed into (39 xor 31) = 56.
Operation 2: x = 56 + 1 = 57
Operation 3: Pick n = 3, x is transformed into (57 xor 7) = 62.
Operation 4: x = 62 + 1 = 63 i.e. (26 – 1).
So, total number of operations are 4.
Input: x = 7
As 23 -1 = 7.
So, no operation is required.
Approach: Take the smallest number larger than x which is of the form of 2n – 1 say num, then update x = x xor num and then x = x + 1 performing two operations. Repeat the step until x is of the form 2n – 1. Print the number of operations performed in the end.
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
- Convert a String to an Integer using Recursion
- Convert the given BCD to its equivalent Binary form
- Minimum number of operations to convert array A to array B by adding an integer into a subarray
- Minimum decrements to make integer A divisible by integer B
- Cyclic shifts of integer N by another integer m
- Blum Integer
- Find One's Complement of an Integer
- Smallest integer which has n factors or more
- Find whether a given integer is a power of 3 or not
- Square root of an integer
- Replace all ‘0’ with ‘5’ in an input Integer
- Minimum positive integer value possible of X for given A and B in X = P*A + Q*B
- Greatest Integer Function
- Check if two Integer are anagrams of each other
- Highest power of 2 less than or equal to given Integer
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.