Given a binary string str, the task is to print the numbers of steps required to convert it to one by the following operations:
- If ‘S’ is odd add 1 to it.
- If ‘S’ is even divide it by 2.
Input: str = “1001001”
Input: str = “101110”
Number ‘101110’ is even, after dividing it by 2 we get an odd number ‘10111’ so we will add 1 to it. Then we’ll get ‘11000’ which is even and can be divide three times continuously in a row and get ’11’ which is odd, adding 1 to it will give us ‘100’ which is even and can be divided 2 times in a row. As, a result we get 1.
So 8 times the above two operations were required in this number.
Below is the step by step algorithm to solve this problem:
- Initialize the string S as a binary number.
- If the size of the binary is 1, then the required number of actions will be 0.
- If the last digit is 0, then its an even number so one operation is required to divide it by 2.
- After encountering 1, traverse till you get 0, with every digit one operation will take place.
- After encountering 0 after 1 while traversing, replace 0 by 1 and start from step 4 again.
Below is the implementation of above algorithm:
- Count the number of carry operations required to add two numbers
- Find the missing value from the given equation a + b = c
- Find four factors of N with maximum product and sum equal to N | Set 3
- Check if the given 2-D points form T-shape or not
- Maximize the product of four factors of a Number
- Minimum number of elements to be removed to make XOR maximum
- Distinct Prime Factors of Array Product
- Practice for cracking any coding interview
- Queries for number of elements on right and left
- Rearrange the string to maximize the number of palindromic substrings
- Queries to add, remove and return the difference of maximum and minimum.
- Find 'N' number of solutions with the given inequality equations
- Number of balanced bracket subsequence of length 2 and 4
- Number of different positions where a person can stand
- Find the direction from given string
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.
Improved By : Shivi_Aggarwal