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:
- Convert a String to an Integer using Recursion
- Blum Integer
- Find One's Complement of an Integer
- Greatest Integer Function
- Replace all ‘0’ with ‘5’ in an input Integer
- Smallest integer which has n factors or more
- Find whether a given integer is a power of 3 or not
- Minimum positive integer value possible of X for given A and B in X = P*A + Q*B
- Square root of an integer
- Check if two Integer are anagrams of each other
- Check for integer overflow on multiplication
- Check if the given array contains all the divisors of some integer
- Find minimum positive integer x such that a(x^2) + b(x) + c >= k
- Print first k digits of 1/n where n is a positive integer
- Generate all unique partitions of an 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.