Skip to content

Commit 3e80219

Browse files
committed
feat: add rust solution to lc problem: No.1342
No.1342.Number of Steps to Reduce a Number to Zero
1 parent db5015a commit 3e80219

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed

solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,39 @@ func numberOfSteps(num int) int {
167167
}
168168
```
169169

170+
### **Rust**
171+
172+
```rust
173+
impl Solution {
174+
pub fn number_of_steps(mut num: i32) -> i32 {
175+
let mut count = 0;
176+
while num != 0 {
177+
if num % 2 == 0 {
178+
num >>= 1;
179+
} else {
180+
num -= 1;
181+
}
182+
count += 1;
183+
}
184+
count
185+
}
186+
}
187+
```
188+
189+
```rust
190+
impl Solution {
191+
pub fn number_of_steps(mut num: i32) -> i32 {
192+
if num == 0 {
193+
0
194+
} else if num % 2 == 0 {
195+
1 + Solution::number_of_steps(num >> 1)
196+
} else {
197+
1 + Solution::number_of_steps(num - 1)
198+
}
199+
}
200+
}
201+
```
202+
170203
### **...**
171204

172205
```

solution/1300-1399/1342.Number of Steps to Reduce a Number to Zero/README_EN.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,39 @@ func numberOfSteps(num int) int {
160160
}
161161
```
162162

163+
### **Rust**
164+
165+
```rust
166+
impl Solution {
167+
pub fn number_of_steps(mut num: i32) -> i32 {
168+
let mut count = 0;
169+
while num != 0 {
170+
if num % 2 == 0 {
171+
num >>= 1;
172+
} else {
173+
num -= 1;
174+
}
175+
count += 1;
176+
}
177+
count
178+
}
179+
}
180+
```
181+
182+
```rust
183+
impl Solution {
184+
pub fn number_of_steps(mut num: i32) -> i32 {
185+
if num == 0 {
186+
0
187+
} else if num % 2 == 0 {
188+
1 + Solution::number_of_steps(num >> 1)
189+
} else {
190+
1 + Solution::number_of_steps(num - 1)
191+
}
192+
}
193+
}
194+
```
195+
163196
### **...**
164197

165198
```
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
impl Solution {
2+
pub fn number_of_steps(mut num: i32) -> i32 {
3+
let mut count = 0;
4+
while num != 0 {
5+
if num % 2 == 0 {
6+
num >>= 1;
7+
} else {
8+
num -= 1;
9+
}
10+
count += 1;
11+
}
12+
count
13+
}
14+
}

0 commit comments

Comments
 (0)