alorithm/programmers
[JAVA/프로그래머스] Lv1. 자릿수 더하기
Hannana.
2023. 4. 11. 03:26
728x90
반응형
[문제]
[나의 풀이]
import java.util.*;
public class Solution {
public int solution(int n) {
int answer = 0;
String turn = Integer.toString(n);
String[] input = turn.split("");
System.out.println("Hello Java");
for(int i=0; i<input.length; i++) {
int num = Integer.parseInt(input[i]);
answer += num;
}
return answer;
}
public static void main(String[] args){
Solution solution = new Solution();
}
}
(중간 프린트문은 지우는 걸 깜빡함. 아무 의미X)
[다른 사람의 풀이]
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;
}
}
전혀 다른 풀이가 흥미롭다. 나중에 하나씩 분석해봐야겠다.
반응형