leetcode 1342. Number of Steps to Reduce a Number to Zero


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.

 

Example 1:

Input: num = 14
Output: 6
Explanation: 
Step 1) 14 is even; divide by 2 and obtain 7. 
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3. 
Step 4) 3 is odd; subtract 1 and obtain 2. 
Step 5) 2 is even; divide by 2 and obtain 1. 
Step 6) 1 is odd; subtract 1 and obtain 0.

Example 2:

Input: num = 8
Output: 4
Explanation: 
Step 1) 8 is even; divide by 2 and obtain 4. 
Step 2) 4 is even; divide by 2 and obtain 2. 
Step 3) 2 is even; divide by 2 and obtain 1. 
Step 4) 1 is odd; subtract 1 and obtain 0.

Example 3:

Input: num = 123
Output: 12

 

Constraints:

  • 0 <= num <= 10^6

題目大意:給定一個非負整數num,返回將其變為0的步數。如果當前的數是偶數,將其除2,否則將其減去1.

思路:直接模擬,為了提高效率,除2用位運算。

C++代碼1:

 1 class Solution {
 2 public:
 3     int numberOfSteps (int num) {
 4         int cnt = 0;
 5         while (num != 0) {
 6             if (num & 1) //為奇數
 7                 num--;
 8             else
 9                 num >>= 1;
10             cnt++;
11         }
12         return cnt;
13     }
14 };

 

C++代碼二:

一般條件下,如果一個數是奇數,我們將其減去1后,下一步肯定除2,(如(5 - 1)/2=2,用了兩步),而利用位運算,可以直接右移一位,會產生兩步的效果:5 >> 1 = 2.

只要整數num一直減小,在變成0之前,肯定會變成1. 當數為1時,步數會多算1.

class Solution {
public:
    int numberOfSteps (int num) {
        int cnt = 0;
        while (num != 0) {
            cnt += (num & 1) ? 2 : 1;
            num >>= 1;
        }
        return cnt - 1;
    }
};

 

 python3代碼:

1 class Solution:
2     def numberOfSteps (self, num: int) -> int:
3         cnt = 0
4         while num != 0: 
5             num, cnt = num - 1 if num % 2 else num // 2, cnt + 1
6         return cnt

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM