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. 마무리
이번 문제는 다른 유저 답변과 비교해도 거의 비슷했다.
어렵지 않게 풀 수 있었던 것 같다.
'알고리즘 > 해결' 카테고리의 다른 글
LeetCode771. Jewels and Stones (0) | 2020.02.23 |
---|---|
LeetCode1351. Count Negative Numbers in a Sorted Matrix (0) | 2020.02.16 |
LeetCode1295. Find Numbers with Even Number of Digits (0) | 2020.02.02 |
LeetCode1313. Decompress Run-Length Encoded List (0) | 2020.02.02 |
LeetCode977. Squares of a Sorted Array (0) | 2020.01.26 |