본문 바로가기

프로그래머스/lv1

자릿수 더하기

/* 자릿수 더하기
 * 자연수 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

'프로그래머스 > lv1' 카테고리의 다른 글

정수 제곱근 판별  (0) 2022.12.13
자연수 뒤집어 배열로 만들기  (0) 2022.12.13
평균 구하기  (0) 2022.12.08
약수의 합  (0) 2022.12.08
짝수와 홀수  (0) 2022.12.08