반응형
https://leetcode.com/problems/add-digits/description/
Add Digits - LeetCode
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, retu
leetcode.com
simulation으로 해결한 문제였습니다.
📕 풀이방법
📔 풀이과정
자리수를 확인해 더해주기 위해 문자열로 바꾼 후 더한 값을 새롭게 갱신해주는 방식으로 while문을 수행합니다.
📔 정답출력
최종 결과값을 정수로 바꿔 반환해줍니다.
📕 Code
📔 C++
class Solution {
public:
int addDigits(int num) {
string digit = to_string(num);
while(digit.size() > 1) {
int sum = 0;
for(auto d : digit) {
sum += d - '0';
}
digit = to_string(sum);
}
return stoi(digit);
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 1470. Shuffle the Array (0) | 2023.02.06 |
---|---|
(C++) - LeetCode (easy) 283. Move Zeroes (0) | 2023.02.03 |
(C++) - LeetCode (easy) 242. Valid Anagram (0) | 2023.01.20 |
(C++) - LeetCode (easy) 228. Summary Ranges (0) | 2023.01.12 |
(C++) - LeetCode (easy) 225. Implement Stack using Queues (0) | 2023.01.10 |