
using System;
public class Solution {
public int solution(int n) {
int answer = 0;
while(n>0)
{
answer += n % 10; // 나머지 연산을 통한 자릿수 더하기
n=n/10; // 남은 자릿수 제거, 반복문을 빠져나오기 위함
}
return answer;
}
}
while 반복문은 n>0인 동안 계속 실행.
모든 자릿수를 처리할 때까지 반복을 계속.
123을 예로 들면, 처음 반복시 나머지 3
두번째 반복시 나머지 2
마지막 반복시 1이 남고 n을 10으로 나누어서 남은 한 자릿수를 제거, n = 0이 됨.
반복 종료: n이 0이 되었으므로.
이후 최종 반환
using System;
public class Solution {
public int solution(int n) {
int nResult = 0; // 합계를 저장할 변수 초기화
string strValue = n.ToString(); // 정수를 문자열로 변환
for(int i = 0; i < strValue.Length; i++) // 문자열의 각 문자를 순회
{
// 문자를 정수로 변환하고 합계에 더함
nResult += int.Parse(strValue[i].ToString());
}
return nResult; // 최종 합계 반환
}
}