본문 바로가기

프로그래머스/LEVEL 1

[프로그래머스/LEVEL1] 자릿수 더하기

문제

 

https://programmers.co.kr/learn/courses/30/lessons/12931

 

코딩테스트 연습 - 자릿수 더하기

자연수 N이 주어지면, N의 각 자릿수의 합을 구해서 return 하는 solution 함수를 만들어 주세요. 예를들어 N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다. 제한사항 N의 범위 : 100,000,000 이하의 자연수 입출

programmers.co.kr

 

코드

import java.util.*;

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

		while (n != 0) {
			System.out.println(n);
			System.out.println(result);
			result += n % 10;
			n /= 10;
		}

		return result;
    }
}