반응형
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/description/
간단 구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
정답 변수 cnt를 선언 후 0으로 초기화해줍니다.
📔 풀이과정
num이 0이 아닌 동안 while loop를 수행합니다.
1. num이 짝수라면 2로 나눠주고 홀수라면 1을 빼줍니다.
2. cnt++ 합니다.
📔 정답 출력 | 반환
cnt를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
int numberOfSteps(int num) {
int cnt = 0;
while(num) {
if(num % 2 == 0) num /= 2;
else num--;
cnt++;
}
return cnt;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 1351. Count Negative Numbers in a Sorted Matrix (1) | 2024.02.15 |
---|---|
(C++, Python3) - LeetCode (easy) 1346. Check If N and Its Double Exist (1) | 2024.02.13 |
(C++) - LeetCode (easy) 1332. Remove Palindromic Subsequences (0) | 2024.02.06 |
(SQL) - LeetCode (easy) 1327. List the Products Ordered in a Period (0) | 2024.02.01 |
(C++) - LeetCode (easy) 1323. Maximum 69 Number (1) | 2024.01.31 |