반응형
LV. Easy 😎
https://leetcode.com/problems/add-digits/
Add Digits - 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
문제
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 <= 2^31 - 1
문제 해결법
10으로 나눈 몫이 0일 때까지 계속 돌려주는 것을 계속 반복하면 끝!
해결 코드
class Solution {
public:
int addDigits(int num) {
int n = 0;
while (num / 10 != 0) {
n += num % 10;
num = num / 10;
if (num < 10) {
num = n + num;
n = 0;
}
}
return num;
}
};
728x90
'Computer Science > 알고리즘' 카테고리의 다른 글
leetcode 567) Permutation in String (0) | 2022.02.11 |
---|---|
leetcode 532) K-diff Pairs in an Array (0) | 2022.02.09 |
leetcode 389) Find the Difference (0) | 2022.02.07 |
leetcode 80) Remove Duplicates from Sorted Array II (0) | 2022.02.06 |
leetcode 525) Contiguous Array (0) | 2022.02.05 |
댓글