개발/프로그래머스
[프로그래머스/C++] 자릿수 더하기
Dwyw
2022. 11. 7. 08:16
Level1 - 자릿수 더하기
문제
문제 설명
자연수 N이 주어지면, N의 각 자릿수의 합을 구해서 return 하는 solution 함수를 만들어 주세요.
예를들어 N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다.
- N의 범위 : 100,000,000 이하의 자연수
입출력 | 예 |
N | answer |
123 | 6 |
987 | 24 |
입출력 예 #1
문제의 예시와 같습니다.
입출력 예 #2
9 + 8 + 7 = 24이므로 24를 return 하면 됩니다.
풀이
사용언어 : C++
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int solution(int n)
{
//string strData;
//string strTest = to_string(n);
int answer = 0;
if ( n <= 100000000 && n != 0 ){
// for (int i = 0 ; i < strTest.size(); ++i ){
// cout<<strTest[i]<<endl;
// answer += strTest[i]-'0';
// }
while (n>0){
answer += n%10;
n /= 10;
}
}
// [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
//cout<<strTest<<endl;
return answer;
}
출처 : https://school.programmers.co.kr/learn/courses/30/lessons/12931