나의 풀이
import java.util.*;
public class Solution {
public int solution(int n) {
int answer = 0;
String str = n + "";
for (int i = 0; i < str.length(); i++) {
answer += Integer.parseInt(str.substring(i,i+1));
}
return answer;
}
}
int를 String으로 변환하여, 한 글자씩 잘라서 다시 int로 형변환했다.
다른 사람의 풀이
import java.util.*;
public class Solution {
public int solution(int n) {
int answer = 0;
while(true){
answer+=n%10;
if(n<10)
break;
n=n/10;
}
// [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
System.out.println("Hello Java");
return answer;
}
}
출처:https://school.programmers.co.kr/learn/courses/30/lessons/12931/solution_groups?language=java
따로 형변환하지 않고, 10을 나눈 나머지를 구해서 각 자릿수를 더했다.
'CODING > CS, 알고리즘, 자료구조 공부' 카테고리의 다른 글
[프로그래머스] 나머지가 1이 되는 수 찾기 (0) | 2025.05.28 |
---|---|
[프로그래머스] 약수의 합 (0) | 2025.05.27 |
[쉬운코드] Array List 와 Linked List 의 차이 (0) | 2025.05.13 |
[프로그래머스] 평균 구하기 (0) | 2025.05.13 |
[쉬운코드] 큐(queue) 설명 (0) | 2025.05.09 |