Leet Code Daily 2024-05-24 - Number of Steps to Reduce a Number in Binary Representation to One
Solution
Simulation
Code
class Solution {
public:
int numSteps(string s) {
int ans = 0;
while (s != "1") {
if (s[s.size() - 1] == '0') {
s.pop_back();
ans++;
} else {
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == '1') {
s[i] = '0';
if (i == 0) {
s = '1' + s;
break;
}
} else {
s[i] = '1';
break;
}
}
ans++;
}
}
return ans;
}
};