알고리즘

[프로그래머스] 자릿수 더하기(Java) *

muerha 2024. 10. 28. 14:47

 

 

 


 

 

 

나의 풀이

public class Solution {
    public int solution(int n) {
        int answer = 0;

        while(n > 0){
            answer += n % 10; 
            n = n / 10;    
        }

        return answer;
    }
}

 

 

 

다른 사람의 풀이

import java.util.*;

public class Solution {
    public int solution(int n) {
        int answer = 0;

        String str = Integer.toString(n);

        for (int i = 0; i < str.length(); i++) {
            answer += Integer.parseInt(str.substring(i, i + 1));
        }

        return answer;
    }
}

 

str.substring(i, i + 1)은 str 문자열에서 i 번째 인덱스의 문자(즉, 자릿수)를 추출하여 그 문자를 문자열 형태로 반환