//GitHub https://github.com/vellimole0621
1342. Number of Steps to Reduce a Number to Zero
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/
문제 설명
:
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.
=> 주어진 수가 1이 될 때까지, 짝수면 2를 나누고, 홀수면 1를 빼는 과정을 반복해. 반복횟수를 구하라.
내 풀이
:
while문으로 1이 될 때까지, 조건문으로 짝홀 구분해 결과 도출
# https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/
# 1342. Number of Steps to Reduce a Number to Zero
class Solution:
def numberOfSteps(self, num: int) -> int:
if num == 0:
return 0
else:
ans = 1
while (num != 1):
if num % 2 == 0:
num /= 2
else:
num -= 1
ans += 1
return ans
더 나은 풀이(leetcode 참조)
:
if 문이 true 일 경우 작동함을 이용해서, ==을 조건에 사용하지 않았다.
class Solution:
def numberOfSteps(self, num: int) -> int:
c=0
while num>0:
if num%2:
num-=1
else:
num//=2
c+=1
return c
'프로그래밍 > Python' 카테고리의 다른 글
[파이썬 Python/알고리즘] LeetCode - Max Consecutive Ones (0) | 2023.08.28 |
---|---|
[파이썬 Python/알고리즘] LeetCode - Ransom Note (0) | 2023.08.01 |
[파이썬 Python/알고리즘] LeetCode - Fizz Buzz (0) | 2023.07.31 |
[파이썬 Python/알고리즘] LeetCode - Richest Customer Wealth (0) | 2023.07.30 |
[파이썬 Python/알고리즘] LeetCode - Integer to Roman (0) | 2023.07.29 |