N

(Leet Code c++)Add Digits 본문

Leet Code 알고리즘

(Leet Code c++)Add Digits

naeunchan 2021. 7. 29. 15:18
728x90
반응형

258. Add Digits

 

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

 

Example 1:

Input: num = 38 Output: 2 Explanation: The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it.

Example 2:

Input: num = 0 Output: 0

 

Constraints:

  • 0 <= num <= 231 - 1

주어진 num이 한 자리수가 될 때까지 각 자리수를 더하면 된다.

 

class Solution {
public:
    int addDigits(int num) {
        int answer = num;
        
        while(answer >= 10){
            answer = 0;
            
            while(num > 0){
                answer += num % 10;
                num /= 10;   
            }
            num = answer;
        }
        
        return answer;
    }
};
728x90
반응형

'Leet Code 알고리즘' 카테고리의 다른 글

(Leet Code c++)Missing Number  (0) 2021.07.30
(Leet Code c++)Ugly Number  (0) 2021.07.29
(Leet Code c++)Binary Tree Paths  (0) 2021.07.29
(Leet Code c++)Valid Anagram  (0) 2021.07.28
(Leet Code c++)Delete Node in a Linked List  (0) 2021.07.28