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
'코딩 공부 > Leetcode' 카테고리의 다른 글
[Python] 876. Middle of the Linked List (0) | 2025.01.12 |
---|---|
[Python] 1400. Construct K Palindrome Strings (0) | 2025.01.12 |
[Python] 916. Word Subsets (0) | 2025.01.10 |
[Python] 412. Fizz Buzz (0) | 2025.01.10 |
[Python] 2381. Shifting Letters II (0) | 2025.01.09 |