Number of Steps to Reduce a Number in Binary Representation to One LeetCode solution in C++

1
class Solution {
2
public:
3
int numSteps(string s) {
4
int n = 0;
5
bool carry = false;
6
int steps = 0;
7
if (s == "1") return 0;
8
while (s.length() > 0) {
9
int i = s.length() - 1;
10
if (carry) {
11
if (s[i] == '1') {
12
carry = true;
13
s[i] = '0';
14
} else {
15
s[i] = '1';
16
carry = false;
17
}
18
}
19
if (s[i] == '0') {
20
s.pop_back();
21
steps++;
22
} else {
23
carry = true;
24
s.pop_back();
25
steps += 2;
26
}
27
if (s == "1") {
28
if (carry) steps++;
29
break;
30
}
31
}
32
return steps;
33
}
34
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0