새발블로그

[프로그래머스/C++] 더 크게 합치기 본문

Problem Solving/Programmers

[프로그래머스/C++] 더 크게 합치기

EUG 2024. 3. 4. 15:41

문제

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

풀이방법

int -> string : to_string

string -> int : stoi

풀이

 

#include <string>
#include <vector>

using namespace std;

int solution(int a, int b) {
    int answer = 0;
    string numA = to_string(a);
    string numB = to_string(b);
    string result1 = numA+numB;
    string result2 = numB+numA;
    if (result1 >=result2)
    {
        answer = stoi(result1);
    }
    else
    {
        answer = stoi(result2);
    }

    return answer;
}

 

이렇게 풀었다가 문자열끼리 .......대소 비교가 되나? 해서 찾아본 개념들

 

1. 같은 길이 문자열 비교

- 두 문자열이 같은 길이일 경우, 대소 비교 가능 (stoi 함수 안사용해도됨 그렇지만 결과가 Int라 사용함)

2. 다른 길이 문자열

string1[i], string2[i] 이렇게 비교하므로 대소가 다를 수 있음

ex) 6 > 130 -> 6과 1을 비교

ex)12 < 123 -> 긴문자열을 크다고 반환