
나의 풀이
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 번째 인덱스의 문자(즉, 자릿수)를 추출하여 그 문자를 문자열 형태로 반환
'알고리즘' 카테고리의 다른 글
| [프로그래머스] 약수의 합(Java) (0) | 2024.10.29 |
|---|---|
| [프로그래머스] 평균 구하기(Java) (0) | 2024.10.28 |
| [프로그래머스] 짝수와 홀수(Java) (0) | 2024.10.26 |
| [프로그래머스] 배열의 평균값(Java) (0) | 2024.10.25 |
| [프로그래머스] 짝수의 합(Java) (0) | 2024.10.24 |