코딩문제/프로그래머스
1레벨 : 자릿수 더하기
Drill_Labito
2020. 7. 15. 03:08
문자열 처리를 이용한 해결, to_string 으로 정수를 문자열 변환,
이후 string 배열에 있는 값을 하나씩 분리하면서 문자 0의 아스키 코드값을 빼서 정수값으로 처리
이를 result 변수에 더함으로 답을 구함.
#include <iostream>
#include <string>
using namespace std;
int solution(int n)
{
string a = to_string(n);
int result = 0;
for (int i = 0; i < a.size(); i++) {
result += a[i] - '0';
}
return result;
}