개발자 능력치 물약/C++
프로그래머스 레벨0: 두 수의 연산값 비교하기
하시무
2025. 2. 23. 15:18
문제
작성코드
#include <string>
#include <vector>
using namespace std;
int solution(int a, int b) {
int answer = 0;
string ab = to_string(a) + to_string(b);
int mul_ab = 2 * a * b;
int str_ab = stoi(ab);
if(str_ab > mul_ab){
answer = str_ab;
}
else
answer = mul_ab;
return answer;
}
고쳐야 할 점
가독성이 떨어져서 변수선언을 간소화하고 stl 알고리즘의 max함수를 사용했다.
수정코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(int a, int b){
int answer = 0;
string s = to_string(a) + to_string(b);
answer = max(stoi(s), 2 * a * b);
return answer;
}
max() 함수를 사용할때 인자들의 값이 같으면 그 값을 리턴해준다.
번외편)
#include <iostream>
#include <algorithm>
using namespace std;
int solution(int a, int b) {
int multiplier = 1;
int temp = b;
// b가 0일 경우 자릿수는 1이어야 함.
if (temp == 0) {
multiplier = 10;
} else {
while (temp > 0) {
multiplier *= 10;
temp /= 10;
}
}
int concat_ab = a * multiplier + b;
return max(concat_ab, 2 * a * b);
}
to_string, stoi 를 이용해 숫자를 문자열 변환로 변환한뒤 정수로 변환했다. 이 과정이 불필요한 메모리와 연산을 발생시키므로 최적화 할 수 있다. 따라서 정수 연산으로 대체했다.