알고리즘/프로그래머스 1단계

프로그래머스 - 두 수의 합 - C++

게임만드는학생 2023. 7. 29. 22:21

https://school.programmers.co.kr/learn/courses/30/lessons/181846

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

#include <string>
#include <vector>
#include <algorithm>
#include<iostream>
using namespace std;

string solution(string a, string b) {
    string answer = "";
    int i;
    bool ch = false;

    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());

    for (i = 0; i < a.length() && i<b.length(); i++)
    {
        char num = ((a[i] - '0') + (b[i] - '0'))+'0';
        if (ch)num++;
        ch = false;
        if (num > 57)
        {
            ch = true;
            answer += ((num - '0') % 10+'0');
        }
        else answer += num;
    }
    // a가 안끝났으면
    while (i < a.length())
    {
        char num = a[i];
        if (ch)num++;
        ch = false;
        if (num > 57)
        {
            ch = true;
            answer += ((num - '0') % 10 + '0');
        }
        else answer += num;
        i++;
    }
    // b가 안끝났으면
    while (i < b.length())
    {
        char num = b[i];
        if (ch)num++;
        ch = false;
        if (num > 57)
        {
            ch = true;
            answer += ((num - '0') % 10 + '0');
        }
        else answer += num;
        i++;
    }
    if (ch)answer += 1+'0';
    reverse(answer.begin(), answer.end());
    return answer;
}

 

설명

 

풀 때, 10만자리의 숫자까지 가능하기 때문에 int나 long long 으로 바꿔서 계산하는 것은 불가능하다. 

따라서 1자리씩 따로따로 계산해서 그 결과를 문자열로 만들어야 한다. 

 

내가 생각한 알고리즘은 

1. 1자리를 계산하고 10이 넘는지 체크해놓는다.

2. 다음 자리를 계산할 때, 이전 숫자가 10이 넘었는지 보고 덧셈에 1을 더한다. 

3. 두 개의 숫자가 자릿수가 달랐으면 나머지 수를 채운다. 

이다. 

 

구현할 때, 알아야할 사실

1. 숫자를 문자로 바꾸는 방법 

int a = 2; 
char c;

c = a + '0';

숫자를 문자로 바꿀 때, '0' 을 붙이면 문자 0 으로 된다. 

 

2. 문자를 숫자로 바꾸는 방법

int a; 
char c = '2';

a = c - '0';

마찬가지로 문자를 숫자로 만들때는 '0' 을 빼면 숫자가 된다. 

 

 

 

다른 방법( 다른사람의 풀이에서 가져왔다.)

#include <string>
#include <vector>
#include <iostream>

using namespace std;

string solution(string a, string b) {
    int alen = a.length();
    int blen = b.length();
    int carry = 0;
    string answer = "";
    for(int i = 1; i <= max(alen, blen); i++)
    {
        int numa = (i > alen)? 0 : a[alen-i]-'0';
        int numb = (i > blen)? 0 : b[blen-i]-'0';
        int num = numa + numb + carry;

        if   (num >= 10) carry = 1;
        else             carry = 0;

        char numc = num%10+'0';
        answer = numc + answer;
    }

    if(carry) answer = "1"+answer;
    return answer;
}

더 작은 수까지 반복문을 돌고 이 후에 큰 수를 대입하는 건 동일한데, 반복문을 다시 쓰지 않고 한 곳에서 i를 판단해서 값을 대입한다. 그리고 문자열을 answer += num 이 아닌 num + answer 로 함으로써 굳이 reverse를 할 필요가 없어졌다.