CODING/CS, 알고리즘, 자료구조 공부
[프로그래머스] 자릿수 더하기
codingTrip
2025. 5. 14. 10:40
나의 풀이
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을 나눈 나머지를 구해서 각 자릿수를 더했다.