0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LeetCodeの1342.Number of Steps to Reduce a Number to Zeroについて

Posted at

LeetCodeの1342.Number of Steps to Reduce a Number to Zeroについて

自分で思いついた解法はこれ。

qiita.py
def numberOfSteps(num):
    steps = 0
    while num > 0:
        if num % 2 == 1:
            num -= 1
        elif num % 2 == 0:
            num //= 2
        steps += 1
    return steps

numberOfSteps(14)
6

使う知識としては、
最初にsteps = 0を設定すること
whileループ
if/else制御構文かな

初心者っぽい考えかもしれないけど
WhileとForの使い分けとしては

whileは既定の値になるまでループを繰り返す
forはリストの要素を1つずつ順に見ていく

という感じでしょうか

インデックスの扱いがようやく少し掴めてきた今日この頃...

もっとたくさん解いていきたい

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?