close
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.
解題想法:
要求計算以二為底的次方數
大多數網路上的方法採用的應該是計算二進制1數量
我想或許用遞迴寫比較高端
不過不太會寫遞迴卡了一陣子
最後翻了一下解答看其他人的作法才抄作業完成
Python code:
class Solution: def numberOfSteps (self, num: int) -> int: def numberOfSteps(num: int, step: int) -> int: if num == 0: return step elif num % 2 == 1: step += 1 return numberOfSteps(num - 1,step) else: step += 1 return numberOfSteps(num / 2,step) return numberOfSteps(num, 0)
文章標籤
全站熱搜
留言列表