코딩 공부/Leetcode

[Python] 1342. Number of Steps to Reduce a Number to Zero

일하는 공학도 2025. 1. 11. 12:42
728x90

The LeetCode Beginner's Guide의 Challenge Problems에서 4번째로 나온 문제.

짝수일 때는 2분의 1로 나누는 step과, 홀수일 때는 1을 빼서 짝수로 만드는 step을 반복하여

0이 될때까지 몇 번의 step을 거치는 지 계산하라는 문제.

 

class Solution(object):
    def numberOfSteps(self, num):
        """
        :type num: int
        :rtype: int
        """
        tem = 0
        while num > 0:
            if num % 2 == 0:
                num = num / 2
                tem += 1
            else:
                num -= 1
                tem += 1
        return tem

1. 0이 될때까지 반복하는 while문을 설정

2. num을 2로 나눴을 때 나머지가 0(짝수)이 되는 경우와,

3. 나머지가 1(홀수)의 경우에 따라 계산

728x90