const getGreatestCommonDivisor = (a, b) => {
if (b) {
const newA = b;
const newB = a % b;
return getGreatestCommonDivisor(newA, newB);
}
return a;
};
const getLowestCommonMultiple = (a, b) => {
return (a * b) / getGreatestCommonDivisor(a, b);
};
const sortHelper = (a, b) => {
const aToStr = a.toString();
const bToStr = b.toString();
if (aToStr.length != bToStr.length) {
const LCM = getLowestCommonMultiple(aToStr.length, bToStr.length);
const multipledA = parseInt(aToStr.repeat(LCM / aToStr.length));
const multipledB = parseInt(bToStr.repeat(LCM / bToStr.length));
if (multipledA > multipledB) {
return -1;
}
if (multipledA < multipledB) {
return 1;
}
}
if (a > b) {
return -1;
}
if (a < b) {
return 1;
}
return 0;
};
const solution = (numbers) => {
const result = numbers.sort(sortHelper).join("");
if (parseInt(result) == 0) {
return "0";
}
return result;
};
생각보다 최대공약수, 최소공배수가 쓰일 일이 있으니 유클리도 호제는 외워두는 게 좋겠다.
마지막 예외처리를 실전에서 생각해낼 수 있을까 모르겠다.
다른 사람의 풀이를 보니 이걸 함수형으로 풀어낸 사람이 있다;;
비록 실행 시간은 좀 더 걸리긴 하지만 코드도 7줄 밖에 안되고 훨씬 명료하고 직관적이다
그리고 무엇보다 최소공배수 같은 걸 구하지 않고도 비교 기준을 세운 게 대단하다 ㅠㅠ
(아니 근데 나 빼고는 다 이렇게 풀었네)
const sortHelper = (a, b) => {
const aToStr = a.toString();
const bToStr = b.toString();
if (aToStr.length != bToStr.length) {
const aFirst = aToStr + bToStr;
const bFirst = bToStr + aToStr;
if (aFirst > bFirst) {
return -1;
}
if (aFirst < bFirst) {
return 1;
}
}
if (a > b) {
return -1;
}
if (a < b) {
return 1;
}
return 0;
};
const solution = (numbers) => {
const result = numbers.sort(sortHelper).join("");
if (parseInt(result) == 0) {
return "0";
}
return result;
};