반응형

https://leetcode.com/problems/add-digits/description/

 

Add Digits - LeetCode

Can you solve this real interview question? 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 -->

leetcode.com

 

반복문을 이용하여 num이 한 자릿수가 될 때까지 연산을 수행하였습니다.

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

+ Recent posts