본문 바로가기

문제풀이

[C언어] 백준 11720

 

#include <stdio.h>

int main(void)
{
    int n, sum = 0;
    char nums[100] = { '\0' };

    scanf("%d", &n);      //get the number of numbers to be entered
    scanf("%s", nums);    //get the number as c-string to prevent overflow

    for (; n; n--)
        sum += (int)(nums[n - 1] - '0'); // convert char to int

    printf("%d", sum);

    return 0;
}
  • 문제유형: 문자열
    • 100자리까지의 정수를 저장해야 하기 때문에 unsigned long long으로 인풋을 저장할 수 없음
  • 접근
    • char array로 값을 입력받아 요소 하나하나를 꺼내 int로 형변환 후 sum을 구해야 함
    • How to convert char to int
      • typecasting
        • The simplest way to resolve this problem
        • get the element and subtract the integer value of character '0' from the element
        • nums[n-1] returns the numeric character(1-100 but of char type)
          • ex. '3' will have different decimal values depending on the collating sequence
            • ASCII: 51 ('0' - 48)
            • EBCDIC: 243('0'-240)
          • However, in all the collating sequences, the difference between a decimal number and another decimal number will be the same.
          • 어떤 부호체계에서도(숫자가 48에서 시작하든 240에서 시작하든)  0-9까지의 수는 연속적으로 나열되어 있기 때문에 '0'과의 차이를 구하면 integer value를 알 수 있음
      • atoi
        • <stdlib.h> 라이브러리의 atoi, atol를 사용하면 int, long type의 정수로까지 변환 가능
        • int __cdecl atoi(const char *_String)
          • 그러나 프로토타입에서 알 수 있듯, 애초에 c-string 문자열('\0' 포함)을 알규먼트로 받아 int로 변환한다
          • 따라서 문자열(char*)이 아닌 문자 하나 char씩을 정수형으로 변환시키는 데 쓰기엔 애매하다
      • sscanf, sprintf
        • atoi처럼 c-string 자체를 정수로 바꾸는데 쓸 수는 있는데... 여기서 얻고자 하는 값은 1 digit이라 패스함
  • 사실 이 문제를 문자열을 쓰지 않고 scanf의 modifier을 바꿔 코드를 좀더 단순화할 수 있다.
  • #include <stdio.h>
    
    int main(void)
    {
        int n, num, sum = 0;
    
        scanf("%d", &n);      //get the number of numbers to be entered
    
        for (; n; n--)
        {
            scanf("%1d", &num);    //get the number by one digit
            sum += num;
        }
    
        printf("%d", sum);
    
        return 0;
    }

'문제풀이' 카테고리의 다른 글

[C언어] 백준 1152 단어의 개수  (0) 2021.12.22
[C언어] 백준 1157 단어공부  (0) 2021.12.22
[C언어] 백준 2675 문자열반복  (0) 2021.12.21
[C언어] 백준 10809 알파벳찾기  (0) 2021.12.21
[C언어] 백준 15596  (0) 2021.12.20