Skip to content

Commit a5021d8

Browse files
committed
day 12
1 parent 8fa2a6b commit a5021d8

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Number of Steps to Reduce a Number to Zero
3+
==========================================
4+
5+
Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
6+
7+
Example 1:
8+
Input: num = 14
9+
Output: 6
10+
Explanation:
11+
Step 1) 14 is even; divide by 2 and obtain 7.
12+
Step 2) 7 is odd; subtract 1 and obtain 6.
13+
Step 3) 6 is even; divide by 2 and obtain 3.
14+
Step 4) 3 is odd; subtract 1 and obtain 2.
15+
Step 5) 2 is even; divide by 2 and obtain 1.
16+
Step 6) 1 is odd; subtract 1 and obtain 0.
17+
18+
Example 2:
19+
Input: num = 8
20+
Output: 4
21+
Explanation:
22+
Step 1) 8 is even; divide by 2 and obtain 4.
23+
Step 2) 4 is even; divide by 2 and obtain 2.
24+
Step 3) 2 is even; divide by 2 and obtain 1.
25+
Step 4) 1 is odd; subtract 1 and obtain 0.
26+
27+
Example 3:
28+
Input: num = 123
29+
Output: 12
30+
31+
Constraints:
32+
0 <= num <= 10^6
33+
34+
Hint #1
35+
Simulate the process to get the final answer.
36+
*/
37+
38+
class Solution
39+
{
40+
public:
41+
int numberOfSteps(int num)
42+
{
43+
if (num == 0)
44+
return 0;
45+
int ans = 0;
46+
if (num % 2 == 0)
47+
ans += numberOfSteps(num / 2);
48+
else
49+
ans += numberOfSteps(num - 1);
50+
return ans + 1;
51+
}
52+
};

‎Leetcode Daily Challenge/February-2021/README.MD‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,6 @@
1313
| 9. | [Convert BST to Greater Tree](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/585/week-2-february-8th-february-14th/3634/) | [cpp](./09.%20Convert%20BST%20to%20Greater%20Tree.cpp) |
1414
| 10. | [Copy List with Random Pointer](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/585/week-2-february-8th-february-14th/3635/) | [cpp](./10.%20Copy%20List%20with%20Random%20Pointer.cpp) |
1515
| 11. | [Valid Anagram](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/585/week-2-february-8th-february-14th/3636/) | [cpp](./11.%20Valid%20Anagram.cpp) |
16+
| 12. | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/585/week-2-february-8th-february-14th/3637/) | [cpp](./12.%20Number%20of%20Steps%20to%20Reduce%20a%20Number%20to%20Zero.cpp) |
1617

1718

0 commit comments

Comments
 (0)