Coding Problem/백준

[백준] 10757 - 큰수 A+B

마탁이 2021. 4. 17. 18:59

www.acmicpc.net/problem/10757

 

10757번: 큰 수 A+B

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

www.acmicpc.net

  • 로직은 간단하게 생각했으나 std::atoi()의 특성을 제대로 이해하지 않고 사용해 시간이 걸렸던 문제
  • atoi는 char형 포인터를 문자열로 받는데 이때 1 byte의 char만 입력한다면 뒤에 null이 들어가지 않아 값이 다를 경우가 발생할 수 있다.

더보기
#include <iostream>
#include <cstring>
#include <stdlib.h>

// define
#define MAX_LEN 10002

int main()
{
	// init
	std::ios::sync_with_stdio(false);

	// input
	char A[MAX_LEN] = { '\0', };
	char B[MAX_LEN] = { '\0', };
	char result[MAX_LEN + 1] = { '\0', };
	(void)scanf("%s %s", &A, &B);

	const int ALen = std::strlen(A);
	const int BLen = std::strlen(B);
	const int longgerLen = ALen > BLen ? ALen : BLen;
	
	// reverse
	char reA[MAX_LEN] = { '\0', };
	char reB[MAX_LEN] = { '\0', };

	int AMaxIdx = (ALen - 1);
	for (int idx = 0; idx < ALen; idx++ )
	{
		reA[idx] = A[AMaxIdx];
		AMaxIdx--;
	}

	int BMaxIdx = (BLen - 1);
	for (int idx = 0 ; idx < BLen; idx++)
	{
		reB[idx] = B[BMaxIdx];
		BMaxIdx--;
	}

	// calc
	int overflow = 0;
	for (int idx = 0; idx < longgerLen; idx++)
	{
		char aBuf[2] = { "\0", };
		char bBuf[2] = { "\0", };
		aBuf[0] = reA[idx];
		bBuf[0] = reB[idx];

		int aVal = std::atoi(aBuf);
		int bVal = std::atoi(bBuf);
		int plusVal = aVal + bVal;

		if (true == overflow)
		{
			plusVal += overflow;
			overflow = 0;
		}

		if (10 <= plusVal)
		{
			plusVal -= 10;
			overflow = 1;
		}

		char convertBuf[2] = { '\0', };
		sprintf(convertBuf, "%d", plusVal);
		result[idx] = convertBuf[0];

		if (idx == (longgerLen - 1) && 1 == overflow)
		{
			char convertBuf[2] = { '\0', };
			sprintf(convertBuf, "%d", overflow);
			result[idx+1] = convertBuf[0];
		}
	}

	// print
	char reResult[MAX_LEN + 1] = { '\0', };
	const int resultLen = std::strlen(result);
	int resultMaxIdx = (resultLen - 1);
	for (int idx = 0; idx < resultLen; idx++)
	{
		reResult[idx] = result[resultMaxIdx];
		resultMaxIdx--;
	}

	printf("%s\n", reResult);

	return 0;
}

'Coding Problem > 백준' 카테고리의 다른 글

[백준] 2447 - 별 찍기 - 10  (0) 2021.04.29
[백준] 11653 - 소인수분해  (0) 2021.04.17
[백준] 11004번 - K번째 수  (0) 2021.01.26
[백준] 1977 - 완전제곱수  (0) 2021.01.22
[백준] 1463 - 1로 만들기  (0) 2021.01.19