본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1342. Number of Steps to Reduce a Number to Zero

반응형

https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

간단 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

정답 변수 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;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.