Problem Solving
[C++] [leetCode 258] Add Digits (pps 4-6)
tls1107
2021. 7. 18. 01:08
728x90
반응형
문제 풀기 전 생각 :
/*
재귀 함수를 사용해서 풀기로 생각했다.
숫자가 입력되면 그 숫자를 string 타입으로 변환하고
변환된 string을 쪼개서 모두 더하고 더한 것을 재귀함수 형식으로 콜한다.
그리고 만약 입력된 숫자가 10보다 작다면 리턴한다.
*/
#include <string>
class Solution {
public:
int addDigits(int num) {
if(num < 10) return num;
string s = to_string(num);
int answer = 0;
for(int i=0 ; i<s.length() ; i++){
answer += (int)(s[i] - '0');
}
return addDigits(answer);
}
};
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
풀 때 어려웠던 점 또는 느낀점 :
어렵지 않았다.
to_string 함수와 atoi 함수에 대해 공부할 수 있는 기회였다.
개선방안 :
class Solution {
public:
int addDigits(int num) {
int n=num;
string s=to_string(num);
int len=s.size();
while(len!=1)
{
int su=0;
for(int i=0;i<s.size();i++)
{
su+=s[i]-'0';
}
s=to_string(su);
len=s.size();
}
return stoi(s);
}
};
위의 코드는 재귀함수를 사용하지 않고 푼 경우다
이런 방법도 있다는 것을 알아간다
728x90
반응형