본문 바로가기
IT/알고리즘

5] Leetcode 1342. Number of Steps to Reduce a Number to Zero

by 깻잎쌈 2020. 6. 21.
반응형
 

Number of Steps to Reduce a Number to Zero - LeetCode

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

주어진 숫자를

짝수면 반으로 나누고, 홀수면 -1해서 

0으로 만드는데 걸리는 연산 횟수를 반환하는 문제다.

 

class Solution {
public:
    int numberOfSteps (int num) {
        int ans = 0;
        while(num !=0){
            if(num %2 == 0){
                num /=2;
                ans++;
            }
            else{
                num--;
                ans++;
            }
        }
        
        return ans;
    }
};

주어진 규칙 그대로 해주면 된다.

반응형

댓글