You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/1400-1499/1404.Number of Steps to Reduce a Number in Binary Representation to One/README_EN.md
+85-4Lines changed: 85 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -43,9 +43,9 @@ tags:
43
43
Step 1) 13 is odd, add 1 and obtain 14.
44
44
Step 2) 14 is even, divide by 2 and obtain 7.
45
45
Step 3) 7 is odd, add 1 and obtain 8.
46
-
Step 4) 8 is even, divide by 2 and obtain 4.
46
+
Step 4) 8 is even, divide by 2 and obtain 4.
47
47
Step 5) 4 is even, divide by 2 and obtain 2.
48
-
Step 6) 2 is even, divide by 2 and obtain 1.
48
+
Step 6) 2 is even, divide by 2 and obtain 1.
49
49
</pre>
50
50
51
51
<p><strongclass="example">Example 2:</strong></p>
@@ -54,7 +54,7 @@ Step 6) 2 is even, divide by 2 and obtain 1.
54
54
<strong>Input:</strong> s = "10"
55
55
<strong>Output:</strong> 1
56
56
<strong>Explanation:</strong> "10" corresponds to number 2 in their decimal representation.
57
-
Step 1) 2 is even, divide by 2 and obtain 1.
57
+
Step 1) 2 is even, divide by 2 and obtain 1.
58
58
</pre>
59
59
60
60
<p><strongclass="example">Example 3:</strong></p>
@@ -81,7 +81,15 @@ Step 1) 2 is even, divide by 2 and obtain 1.
81
81
82
82
### Solution 1: Simulation
83
83
84
-
We simulate operations $1$ and $2$, while using `carry` to record the carry-over.
84
+
We simulate operations $1$ and $2$, while maintaining a carry $\textit{carry}$ to indicate whether there is a current carry. Initially, $\textit{carry} = \text{false}$.
85
+
86
+
We traverse the string $s$ from the end toward the beginning:
87
+
88
+
- If $\textit{carry}$ is $\text{true}$, the current bit $c$ needs to be incremented by $1$. If $c$ is $0$, it becomes $1$ after adding $1$, and $\textit{carry}$ becomes $\text{false}$; if $c$ is $1$, it becomes $0$ after adding $1$, and $\textit{carry}$ remains $\text{true}$.
89
+
- If $c$ is $1$, we need to perform operation $1$, i.e., add $1$, and $\textit{carry}$ becomes $\text{true}$.
90
+
- At this point $c$ is $0$, so we need to perform operation $2$, i.e., divide by $2$.
91
+
92
+
After the traversal, if $\textit{carry}$ is still $\text{true}$, we need to perform operation $1$ one more time.
85
93
86
94
The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.
87
95
@@ -199,6 +207,79 @@ func numSteps(s string) int {
0 commit comments