/* 자릿수 더하기
* 자연수 N이 주어지면, N의 각 자릿수의 합을 구해서 return 하는 solution 함수를 만들어 주세요.
* 예를들어 N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다.
*
* N answer
* 123 6
* 987 24
*/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class programmer_1_10 { static int a1 = 123; static int a2 = 987; public int solution(int n) { int answer = 0; String k = Integer.toString(n); for(int i = 0; i < k.length(); i++){ answer += Integer.parseInt(k.substring(i,i+1)); } return answer; } public static void main(String args[]){ programmer_1_10 t = new programmer_1_10(); System.out.println("---------------------------------------"); System.out.println("result = " + t.solution(a1)); System.out.println("---------------------------------------"); System.out.println("result2 = " + t.solution(a2)); System.out.println("---------------------------------------"); } } | cs |