1. 문제
문제 설명
자연수 N이 주어지면, N의 각 자릿수의 합을 구해서 return 하는 solution 함수를 만들어 주세요. 제한사항
|
2. 나의 풀이
import java.util.*;
public class Solution {
public int solution(int n) {
int answer = 0;
int imsi = n;
for(int i = 1; i <= (int)(Math.log10(n)+1); i = i + 1) {
System.out.println(answer);
answer += imsi % 10;
imsi = imsi / 10;
}
return answer;
}
}
3. 다른 사람 풀이
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;
}
}
'알고리즘 공부 > 프로그래머스' 카테고리의 다른 글
프로그래머스 코딩테스트 연습 - 연습문제 - 정수 내림차순으로 배치하기 (0) | 2020.10.06 |
---|---|
프로그래머스 코딩테스트 연습 - 연습문제 - 자연수 뒤집어 배열로 만들기 (0) | 2020.10.04 |
프로그래머스 코딩테스트 연습 - 연습문제 - 이상한 문자 만들기 (0) | 2020.10.04 |
프로그래머스 코딩테스트 연습 - 연습문제 - 약수의 합 (0) | 2020.10.04 |
프로그래머스 코딩테스트 연습 - 연습문제 - 시저 암호 (0) | 2020.10.03 |