웅재의 코딩세상

[프로그래머스] 두 수의 합 본문

코딩테스트/프로그래머스 - LV 0

[프로그래머스] 두 수의 합

웅드 2024. 2. 1. 21:23

 

 

  • 풀이
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

string solution(string a, string b) {
    string answer ="";
    reverse(a.begin(),a.end());
    reverse(b.begin(), b.end());
    
    if(a.size() < b.size())swap(a,b);
    b.resize(a.size(), '0');
    
    int carry=0;
    for(int i=0; i<a.size(); i++){
        int sum = (a[i]-'0') + (b[i]-'0') + carry;
        carry = sum/10;
        sum %= 10;
        answer += sum + '0';
    }
    if(carry) answer += carry+'0';
    reverse(answer.begin(), answer.end());
    return answer;
}
반응형