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