C언어) 자릿수 더하기_프로그래머스

은영·2021년 7월 29일
0

Programmers

목록 보기
4/4

프로그래머스 Lv_1 자릿수 더하기
(https://programmers.co.kr/learn/courses/30/lessons/12931)


풀이과정

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int solution(int n) {
    int answer = 0;
    return answer;
}

이것이 처음에 주어진 소스코드, solution(int n)의 함수를 작성하면 된다.

  • 주요 풀이 (while 반복문)
    (1)
    answer += 123%10; (answer = 0 + 3 = 3)
    n = 123/10; (n = 12 -> 계속진행)
    (2)
    answer += 12%10; (answer = 3 + 2 = 5)
    n = 12/10; (n = 1 -> 계속 진행)
    (3)
    answer += 1%10; (answer = 5 + 1 = 6)
    n = 1/10; (n = 0 -> 반복 중단)

정답 소스코드 (C언어)

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int solution(int n) {
    int answer = 0;
    while(n>0){
        answer += n % 10;
        n /= 10;
    }
    return answer;
}

Visual studio 2019 환경에서 main 함수를 포함하여 작성한 소스 코드

/*자릿수 더하기
 https://programmers.co.kr/learn/courses/30/lessons/12931 */

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int solution(int n) {
    int answer = 0;
    while (n > 0) {
        answer += n % 10;
        n /= 10;
    }
    return answer;
}

int main(void) {
    int n;
    
    printf("n의 값 입력: ");
    scanf_s("%d", &n);
    printf("각 자리수 더한 값: %d \n", solution(n));
    
    return 0;
}

디버그 결과

profile
Leyn(레인)

0개의 댓글