728x90
삼성 SW Expert Academy
문제 2058. 자릿수 더하기
링크

https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=1&contestProbId=AV5QPRjqA10DFAUq&categoryId=AV5QPRjqA10DFAUq&categoryType=CODE&problemTitle=&orderBy=RECOMMEND_COUNT&selectCodeLang=JAVA&select-1=1&pageSize=10&pageIndex=1 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

조건

하나의 자연수를 입력 받아 각 자릿수 합을 계산

단, N은 1이상 9999이하 자연수

입력

자연수 N이 주어짐

6789

출력

각 자릿수 합 출력

30

예상분석

1. 입력받은 N을 10으로 나눈 몫을 N에 저장.

2. N을 10으로 나눈 나머지를 cnt에 누적.

3. N<0이 될때까지 반복한다.

코드
import java.util.Scanner;

class Solution
{
    public static void main(String args[]) throws Exception {

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int cnt = 0;

        while (N>0) {
            cnt += N%10;
            N /= 10;
        }

        System.out.println(cnt);

        sc.close();
    }
}
728x90

+ Recent posts