알고리즘/해결

LeetCode1342. Number of Steps to Reduce a Number to Zero

언클린 2020. 2. 16. 14:17
728x90

1. 문제(원본)

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

2. 문제

임의의 Int형 수를 받아 0으로 만드는데 걸리는 Step수를 구하라

(나누기2 와 빼기1을 사용할 수 있다.)

 

3. 나의 답

class Solution {

    func numberOfSteps (_ num: Int) -> Int {

        var number = num

        var step: Int = 0

        while number > 0 {

            number = number % 2 == 0 ? number / 2 : number - 1

            step += 1

        }

        return step

    }

}

4. 다른 유저의 답

#1

class Solution {

    func numberOfSteps (_ num: Int) -> Int {

        var steps = 0

        var currentNum = num

        while currentNum != 0 {

            steps += 1

            if currentNum % 2 == 0 {

                currentNum = currentNum / 2

            } else {

                currentNum -= 1

            }

        }

        return steps

    }

}

5. 마무리

이번 문제는 다른 유저 답변과 비교해도 거의 비슷했다.

어렵지 않게 풀 수 있었던 것 같다.

728x90