프로그래머스 - LV1. 자릿수 더하기

김소정·2022년 3월 2일
0

프로그래머스

목록 보기
14/35

❔ 문제

❗ 내 풀이

import java.util.*;

public class Solution {
    public int solution(int n) {
        int answer = 0;
        String[] str = String.valueOf(n).split("");
        
        for(int i = 0; i < str.length; i++){
            answer += Integer.parseInt(str[i]);
        }

        return answer;
    }
}

🚩참고 (다른 풀이)


1. 
import java.util.*;

public class Solution {
    public int solution(int n) {
        int answer = 0;

        while(true){
            answer+=n%10;	// 형변환없이 이렇게 10으로 나누어서도 전체 합을 구할 수 있구나.
            if(n<10)
                break;

            n=n/10;
        }

        return answer;
    }
}

2.
import java.util.*;

public class Solution {
    public int solution(int n) {
        int answer = 0;

        while (n != 0) {
            answer += n % 10;
            n /= 10;
        }

        return answer;
    }
}


📝 정리

💬 형변환 없이 10으로 나눈 나머지의 합을 구해도 된다.


profile
개발자 가보자고

0개의 댓글

관련 채용 정보