[leetcode] 4

1 minute read

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

Problem

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

Input: num = 14
Output: 6
Explanation:
Step 1) 14 is even; divide by 2 and obtain 7. 짝수 /2 count+1
Step 2) 7 is odd; subtract 1 and obtain 6.    홀수 -1 count+1
Step 3) 6 is even; divide by 2 and obtain 3.  짝수 /2 +
Step 4) 3 is odd; subtract 1 and obtain 2.    홀수 -1 +
Step 5) 2 is even; divide by 2 and obtain 1.  짝수 /2
Step 6) 1 is odd; subtract 1 and obtain 0.    홀수 -1

해석

주어진 숫자를 0으로 만드는 단계를 구하는 문제이다. 주어진 숫자 또는 단계를 거친 결과가 짝수이면 /2 를 하고 +1step을 홀수이면 -1 을 한후 +1setp을 한다. 그래서 주어진 숫자가 0 이 되는 순간까지 거친 총 step의 숫자를 구하는 것이다

Solution in JavaScript

var numberOfSteps = function (num) {
  var count = 0;
  while (num > 0) {
    if (num % 2 == 1) {
      num = num - 1;
      count++;
    } else {
      num = num / 2;
      count++;
    }
  }
  return count;
};

Solution in Java

class Solution {
    public int numberOfSteps (int num) {
        int step=0;
        while(num>0){   for문에 초기값을 주지않고
            if(num%2==0){  짝수일 경우
                step++;
                num/=2;
            }
            else{          홀수일 경우
                num-=1;
                step++;
            }
        }
        return step;
    }
}

Updated: