-
백준 알고리즘, 11720 문제Algorithms/ACM_ICPC 2018. 7. 13. 12:27
이 문제 는 숫자의 합을 구하는 문제다.
입력 조건은 다음과 같다.
1. 숫자의 자리수를 입력한다.
2. 해당 자리수의 수를 입력한다.
unsigned int 자료형의 최대 범위인 -2,147,483,648 ~ 2,147,483,647 을 넘는 범위까지 수용하기 위해서
char 형으로 데이터를 받은 후, int 형으로 캐스팅 해주려고 했다.
/** * @site: https://www.acmicpc.net/problem/11720 * @auth: Landon Park
* @github: https://github.com/7772 * @date: 2018. 07. 12 */ #include <iostream>
#include <string> #include <stdlib.h> using namespace std; // Bad code int main() { int test_case; int i, sum = 0; string str; cin >> test_case; if(test_case < 1 || test_case > 100) return 0; cin >> str; for(i = 0; i < test_case; i++) { sum += (int)(str[i]); } cout << sum << endl; return 0; } 가장 처음 작성한 코드이다.
main 함수 위에 주석으로 Bad code 라고 달아놓았다. 그 이유는 무엇일까..
사실 문제를 처음 보자마자 이 방식을 떠올려 바로 코딩을 했는데, 모든 테스트 케이스를 통과하는데도 불구하고 백준 사이트의 컴파일러를 통과하지 못했다.
추측컨데, 제한된 시간이나 메모리를 초과했을 가능성이 높다고 판단하고 어느 부분을 고쳐야 할지 고민했다.
긴 문자열을 한번에 받아놓고 이후에 배열을 순회하며 하나씩 접근하는 방식은 기본적으로 stirng 공간이 많이 필요할 것 이다.
항상 엄청나게 큰 입력값에 대응해야 한다고 배웠는데.. 과연 이 방식은 string 이 100개 1000개 와도 올바르게 작동할 수 있을까?
cpp 에서 제공하는 string 자료형의 최대 크기가..........
고작 11 자리 까지만 지원한다는 사실은
최초에 내가 int 형을 포기하고 char 형으로 데이터를 입력받겠다고 생각한 것을 아무짝에도 쓸모없게 만들었다.
크....
다시 작성했다.
// Good code int main() { int test_case; int i, sum = 0; char ch; cin >> test_case; if(test_case < 1 || test_case > 100) return 0; for(i = 0; i < test_case; i++) { cin >> ch; sum += ch - '0'; } cout << sum << endl; }
string 을 이용해 한번에 문자열을 받아드리는 최초 방식과 달리, char 형 하나만을 가지고 반복해서 데이터를 입력받는다.
물론 이 문제에서는 test_case 를 1 ~ 100 사이로 제한했지만, 위 방식은 test_case 의 자료형인 int 형의 최대 길이 즉, signed int 일 경우
최대 4,294,967,295 자리수의 숫자를 더할 수 있게 된다.
(물론 그 더한 값이 int 형의 범위를 넘지 않는다면)
한가지 덧붙이자면
sum += ch - '0';
이 부분은
아스키 코드를 이용한 것이다.
만약 ch 에 문자 1 이 저장되어 있다면 ch 에는 아스키코드 49 가 저장되어 있을 것이다.
여기서, 문자 '0' 의 아스키코드는 48 이므로 49 - 48 = 1 이라는 계산이 된다.
첫 포스팅이라 자세히 써보았는데..
앞으로 점점 양이 줄지 않을까 하는 생각을 한다....
반응형'Algorithms > ACM_ICPC' 카테고리의 다른 글
백준 알고리즘, 11726 문제 (0) 2018.07.18 백준 알고리즘, 1463 문제 (0) 2018.07.17 백준 알고리즘, 입출력 관련문제 (0) 2018.07.17 백준 알고리즘, 1924 문제 (0) 2018.07.16 백준 알고리즘, 11723 문제 (1) 2018.07.13