[LeetCode] Number of Steps to Reduce a Number in Binary Representation to One

1404. Number of Steps to Reduce a Number in Binary Representation to One

Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:

  • If the current number is even, you have to divide it by 2.
  • If the current number is odd, you have to add 1 to it.

It is guaranteed that you can always reach one for all test cases.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int numSteps(string s) {
int res = 0;
while(s.length() > 1) {
if(s.back() == '0') s.pop_back();
else {
int carry = 1, n = s.length();
s.back() = '0';
for(int i = n - 2; i >= 0 and carry; i--) {
if(s[i] == '1') s[i] = '0';
else {
s[i] = '1';
carry = 0;
}
}
if(carry) s = '1' + s;
}
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/24/PS/LeetCode/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.