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

Jongleee·2022년 7월 16일
1

알고리즘

목록 보기
6/39
public class Solution {
    public int solution(int n) {
        int answer = 0;
        // 문자열로 변환하여 각 숫자를 구함
        String[] a=Integer.toString(n).split("");

        // 숫자로 변환하여 한자리씩 더함
        for (int i = 0; i < a.length; i++) {
            answer+=Integer.parseInt(a[i]);
        }
//10으로 나눈 나머지 더해도 될듯?

        return answer;
    }
}

나머지로 구하는 법


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int answer = 0;

        System.out.println("숫자를 입력하시오"); 
        int n = input.nextInt();
 
        while(n > 0){
            answer += n%10;
            n= n/10;
        }
        

while 사용하면 반복 조건 만족하면 계속
for 는 반복 횟수를 알아야

0개의 댓글