Created
December 18, 2020 22:19
-
-
Save sanan-fataliyev/c86d1203a050205bc68a1d85a0bc7083 to your computer and use it in GitHub Desktop.
golang solution for reduce binary string problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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. | |
| */ | |
| package main | |
| func main() { | |
| testcases := map[string]int{ | |
| "0": 0, | |
| "1": 1, | |
| "10": 2, | |
| "11": 3, | |
| "100": 3, | |
| "101": 4, | |
| "100110101001001": 21, | |
| } | |
| for bin, expected := range testcases { | |
| if actual := opcount(bin); actual != expected { | |
| println("testcase failed. bin:", bin, ", want:", expected, ", got:", actual) | |
| } | |
| } | |
| } | |
| func opcount(bin string) int { | |
| count := len(bin) * 2 - 1 | |
| for _, bit := range bin { | |
| count -= int('1' - bit) | |
| } | |
| return count | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment