최대 1 분 소요

Question

Q


Solution

  • 10으로 나눈 나머지는 1의자리숫자가 되고, 10을 나누고 다시 10을나눈 나머지는 10의 자리 숫자가 된다.
  • 위 내용을 n이 0보다 클경우 while문으로 반복시키면 된다.

Cord

#include <iostream>

using namespace std;
int solution(int n)
{
    int answer = 0;

    while (n > 0)
    {
        answer += n % 10;
        n /= 10;
    }

    return answer;
}

다른 사람의 풀이이다. 문자열을 이용하였다.

#include <iostream>
#include <string>

using namespace std;
int solution(int n)
{
    int answer = 0;
    string s = to_string(n);

    for(int i = 0; i < s.size(); i++) answer += (s[i] - '0');
    return answer;
}

Result

Result