백준(BOJ) - 부녀회장이 될테야(2775번) - 파이썬(python), C++

2023. 2. 3. 17:12코딩테스트/백준(BOJ)

import sys
input=sys.stdin.readline


a,b=map(int,input().split())

print(a+b)

파이썬 같은 언어는 10,000자리 정도의 자연수도 자유롭게 다룰 수 있다. A와 B가 최대 10의 만승의 수라도 간단한 코드로 작성가능하지만 C, C++같은 언어라면 그렇지 않다. C++언어로 풀어보자

 

 

#include <iostream>
#include <algorithm>

using namespace std;

int main(void) {

    // string 타입으로 입력 받음
    string a, b;
    cin >> a >> b;

    int lenA = a.length();
    int lenB = b.length();

    // A를 더 긴수로 저장
    if (lenB > lenA) {
        swap(a, b);
        swap(lenA, lenB);
    }

    // 자리수 다르면 0으로 채워서 맞춰줌
    string tmp = "";

    if (lenA != lenB) {
        for (int i = 0; i < (lenA - lenB); i++)
            tmp += "0";
    }
    b = tmp + b;;

    // 1의자리부터 더해서 9가 넘어가면 다음 자리로 1올려줌
    string ans = "";
    int carry = 0; // 올림
    int x, y, digit; // 자리수
    for (int i = lenA - 1; i >= 0; i--) {
        x = a[i] - '0';
        y = b[i] - '0';
        digit = x + y;
        if (carry == 1) {
            digit++;
            carry = 0;
        }
        if (digit > 9)
            carry = 1;
        ans += digit % 10 + '0';
    }

    // 최종 자리수가 늘어나면 앞에 1추가
    if (carry == 1)
        ans += "1";

    // 반대로 출력
    reverse(ans.begin(), ans.end());
    cout << ans;

    return 0;

}

 

728x90