As reported: Microsoft SDE online assessment on Codility (75 minutes, two tasks, Jan 2025), task 2:
int solution(String S)for a binary string — while the number is not zero, divide it by 2 if it is even, otherwise subtract 1; return the number of steps. A solution usingBigIntegerfailed some tests because the string is long.
A string S of length N holds a non-negative number V in binary (it may have leading zeros). Until V becomes 0, repeat:
- if
Vis odd, subtract 1; - if
Vis even, divide it by 2.
Return the number of operations performed.
Example 1
S = "011100" -> 7
V = 28 → 14 → 7 → 6 → 3 → 2 → 1 → 0.
Example 2
S = "111" -> 5
Example 3
S = "1111010101111" -> 22
Constraints: 1 ≤ N ≤ 1 000 000; S consists of '0' and '1'.
Code runner format: one line: S. Implement countOperations(S); the harness prints the result.