풀이과정
자연수 n을 string으로 바꾸고 각 자리수에 '0'을 빼줘서 문자를 숫자로 만든다.
숫자로 만든 것들을 반복문을 돌려 합을 구해준다.
#include <iostream>
using namespace std;
int solution(int n)
{
int answer = 0;
string str = to_string(n);
for(int i = 0; i < str.size(); i++){
answer += str[i] - '0';
}
return answer;
}
'🍞 Problem Solving > Programmers' 카테고리의 다른 글
[프로그래머스][Level1] 정수 내림차순으로 배치하기 c++ (0) | 2022.09.02 |
---|---|
[프로그래머스][Level1] 자연수 뒤집어 배열로 만들기 c++ (0) | 2022.09.02 |
[프로그래머스][Level1] 이상한 문자 만들기 c++ (0) | 2022.09.02 |
[프로그래머스][Level1] 약수의 합 c++ (0) | 2022.09.02 |
[프로그래머스][Level1] 약수의 개수와 덧셈 c++ (0) | 2022.09.02 |