프로그래머스 - 자릿수 더하기

well-life-gm·2021년 11월 6일
0

프로그래머스

목록 보기
40/125

프로그래머스 - 자릿수 더하기

모듈러하면서 더하는 방법으로 풀었는데, 다른 사람 코드를 보니 문자열로 변환해서 푼 사람이 있었다.
참신한 방법인듯.

#include <iostream>

using namespace std;
int solution(int n)
{
    int answer = 0;
    string s = to_string(n);
    for(auto c : s)
        answer += c - '0';

    return answer;
}
#include <iostream>

using namespace std;
int solution(int n)
{
    int answer = 0;
    while(n != 0) {
        answer += n % 10;
        n /= 10;
    }

    return answer;
}
profile
내가 보려고 만든 블로그

0개의 댓글