728x90
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
숫자가 일의 자리일 때까지 각 자릿수를 더하는 문제
문자열을 사용해서 쉽게 더하는 방식으로 진행했다.
int addDigits(int num) {
string s = to_string(num);
int n = 0;
if(s.size() == 1) return num;
do{
n = 0;
for(int i=0; i<s.size(); i++){
n += s[i] - '0';
}
s = to_string(n);
}while(s.size() > 1);
return n;
}
아니면 그냥 정말 10으로 나누면서 각 자릿수를 더해주는 방식도 있다.
int addDigits(int num) {
int sum = 0;
while(num > 9){
while(num != 0){
sum += num % 10;
num /= 10;
}
num = sum;
sum = 0;
}
return num;
}
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/easy/BinarySearch] Valid Perfect Square (1) | 2022.09.21 |
---|---|
[LeetCode/easy/BinarySearch] Intersection of Two Arrays II (1) | 2022.09.21 |
[LeetCode/easy/BinarySearch] First Bad Version (0) | 2022.09.21 |
[LeetCode/easy/BinarySearch] Sort(x) (0) | 2022.09.20 |
[LeetCode/easy/TwoPointer] Reverse String II (0) | 2022.09.20 |