자릿수 더하기

김현민·2021년 3월 18일
0

Algorithm

목록 보기
42/126
post-thumbnail

문제

코드1 ( 자릿수 나누는 반복문 )


#include <bits/stdc++.h>

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

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

    return answer;
}



코드2 ( string으로 바꿔서 )


#include <bits/stdc++.h>

using namespace std;
int solution(int n)
{
    int answer = 0;
    string temp = to_string(n);
    
    for (int i = 0; i < temp.size(); i++)
    {
        answer += (int)temp[i] - '0';
    }

    return answer;
}
profile
Jr. FE Dev

0개의 댓글