Notice
Recent Posts
Recent Comments
Tags
more
Today
Total
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
관리 메뉴

SW 꿈나무

[Level 1][C] 자릿수 더하기 본문

Algorithm/Programmers

[Level 1][C] 자릿수 더하기

현식 :) 2020. 3. 26. 18:51
  • 문제

    자연수 N이 주어지면. N의 각 자릿수의 합을 구해서 return하는 solution 함수를 만들어 주세요.

    예를 들어, N=123이면 1 + 2 + 3 = 6 을 return 하면 됩니다.

  • 제한 조건

    N은 100,000,000 이하의 자연수

  • Example

    Input 1 : 123
    Input 2 : 987
    Output 1 : 6
    Output 2 : 24
  • Code

    #include <stdio.h>
    #include <stdbool.h>
    #include <stdlib.h>
    
    int solution(int n) {
        int answer = 0;              //answer 선언 및 초기화      
        for(int i=0;i<9;i++) {       //N의 범위의 승수만큼 반복
            answer+=n%10;            //answer에 10%n add
            n/=10;                   //n = n / 10
        }
        return answer;               //answer 반환
    }
Comments