0
0

More than 1 year has passed since last update.

LeetCode easy: 1342. Number of Steps to Reduce a Number to Zero

Last updated at Posted at 2022-07-19

LeetCodeを始めたので記録しています。

解いた問題

Given an integer num, return the number of steps to reduce it to zero.
In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

ざっくり処理の流れを考える

  • while文でnumが0でない状態をtrueとして回す
  • 奇数偶数判定をする
  • それぞれの処理をしてnumに入れる
  • numが0になったときの回数を返す

書いたコード

/**
 * @param {number} num
 * @return {number}
 */
var numberOfSteps = function(num) {
    steps = 0;
    while (num !== 0) {
        if (num%2){
            num--;
        } else {
            num/= 2;
        }
    steps ++;
    }
    steps;
};

Runtime: 102 ms, faster than 22.64% of JavaScript online submissions for Number of Steps to Reduce a Number to Zero.
Memory Usage: 42 MB, less than 49.50% of JavaScript online submissions for Number of Steps to Reduce a Number to Zero.

調べたこと

JSの数字を真偽値として利用する際の注意点

計算式の書き方

  • プラス/マイナス1
    num++;
    num--;

数字を四則演算して再代入
num[+-*/]= 2

修正はしていないけどTimeComplexityについて

今回は繰り返しのたびに数字が小さくなる。
一番回数が増えるパターンは、/2と-1をずっと繰り返すようなもの。
30 15 14 7 6 3 2 1
「2で割る」と「1をひく」 がどちらも同じ回数でてくるため。
2 logn
計算量では係数を取らないためO(logn)

答えを見て修正したこと

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