✅ check
arr.reverse()
str.replace()
arr.splice()
정수 리스트 num_list가 주어질 때, 마지막 원소가 그전 원소보다 크면 마지막 원소에서 그전 원소를 뺀 값을 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 두 배한 값을 추가하여 return하도록 solution 함수를 완성해주세요.
num_list | result |
---|---|
[2, 1, 6] | [2, 1, 6, 5] |
[5, 2, 1, 7, 5] | [5, 2, 1, 7, 5, 10] |
const solution = (num_list) => {
let answer = [...num_list]
const length = num_list.length
if(num_list[length-1] > num_list[length-2]){
answer.push(num_list[length-1]-num_list[length-2])
}if(num_list[length-1] <= num_list[length-2]){
answer.push(num_list[length-1]*2)
}
return answer;
}
function solution(num_list) {
const [a, b] = [...num_list].reverse();
return [...num_list, a > b ? (a-b):a*2];
}
💡 num_list를
reverse
를 활용해 역순으로 하여 첫 두 요소를 [a, b]로 분해 할당한다 !
정수가 담긴 리스트 num_list가 주어집니다. num_list의 홀수만 순서대로 이어 붙인 수와 짝수만 순서대로 이어 붙인 수의 합을 return하도록 solution 함수를 완성해주세요.
num_list | result |
---|---|
[3, 4, 5, 2, 1] | 393 |
[5, 7, 8, 3] | 581 |
const solution = (num_list) => {
let odd = [];
let even = [];
num_list.forEach(el => el % 2 === 0 ? even.push(el) : odd.push(el));
return parseInt(even.join('')) + parseInt(odd.join(''));
}
💡
forEach
로 num_list를 순회하면서 조건에 따라 odd와 even 에push
하여 활용하기 !
두 정수 a, b가 주어질 때 다음과 같은 형태의 계산식을 출력하는 코드를 작성해 보세요.
a + b = c
입력 #1 4 5
출력 #1 4 + 5 = 9
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let input = [];
rl.on('line', function (line) {
input = line.split(' ');
}).on('close', function () {
console.log(Number(input[0])+' + '+Number(input[1])+' = '+ (Number(input[0]) + Number(input[1])));
});
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let a, b;
rl.on('line', function (line) {
// 구조분해할당
[a, b] = line.split(' ').map(Number);
}).on('close', function () {
console.log(`${a} + ${b} = ${a + b}`);
});
💡
let a, b;
로 a와 b를 할당없이 선언해 준 뒤 구조분해할당을 활용한다.
문자열 my_string, overwrite_string과 정수 s가 주어집니다. 문자열 my_string의 인덱스 s부터 overwrite_string의 길이만큼을 문자열 overwrite_string으로 바꾼 문자열을 return 하는 solution 함수를 작성해 주세요.
my_string | overwrite_string | s | result |
---|---|---|---|
"He11oWor1d" | "lloWorl" | 2 | "HelloWorld" |
"Program29b8UYP" | "merS123" | 7 | "ProgrammerS123" |
// 👀 첫 번째 풀이( 오답 ) replace는 해당하는 첫번째 index를 변환한다.
const solution = (my_string, overwrite_string, s) => {
const endIdx = overwrite_string.length;
const edit = my_string.slice(s, s + endIdx);
return my_string.replace(edit, overwrite_string);
}
// ✨ 두 번째 풀이
const solution = (my_string, overwrite_string, s) => {
const start = my_string.slice(0, s);
const end = my_string.slice(s+overwrite_string.length)
return start + overwrite_string + end
}
💡 trouble shooting !
첫 번째 풀이에서replace
는 같은 문자열이 여러 개 검색될 경우 '첫 번째' 검색된 문자열을 치환한다. 이 특징 때문에 정확히s
에 해당하는 문자열이 치환되지 않을 수 있다. 예를 들어 'xxxxxx', 'ooo', 2 가 전달될 경우 'xxooox'가 반환되어야 하지만replace
를 사용할 경우 가장 첫번째로 검색되는 x부터 치환되어 'oooxxx'가 반환된다.replaceAll
을 사용해도 동일한 문자가 모두 바뀌므로 해결되지 않는다 !
그래서 문자열을 overwrite_string을 기준으로 앞과 뒤로 나누었다. 그런 다음 앞과 overwrite_string, 뒤를 순서대로 결합하여 반환해주었다 !
// 배열을 활용한 풀이
function solution(my_string, overwrite_string, s) {
const answer = my_string.split('');
answer.splice(s, overwrite_string.length, overwrite_string);
return answer.join('');
}
💡 my_string을
split
으로 하나하나 잘라서 배열로 만들고splice
를 활용하여 overwrite_string로 바로 교체해주었다.
길이가 같은 두 문자열 str1과 str2가 주어집니다.
두 문자열의 각 문자가 앞에서부터 서로 번갈아가면서 한 번씩 등장하는 문자열을 만들어 return 하는 solution 함수를 완성해 주세요.
str1 | str2 | result |
---|---|---|
"aaaaa" | "bbbbb" | "ababababab" |
const solution = (str1, str2) => {
let result = [];
[...str1].map((el, idx) => {
result.push(el);
result.push(str2[idx]);
})
return result.join('');
}
function solution(str1, str2) {
return [...str1].map((x, idx)=> x+str2[idx]).join("");
}
💡
join('')
하기 전의 배열 :[ 'ab', 'ab', 'ab', 'ab' ]
연산 ⊕는 두 정수에 대한 연산으로 두 정수를 붙여서 쓴 값을 반환합니다. 예를 들면 다음과 같습니다.
단, a ⊕ b와 b ⊕ a가 같다면 a ⊕ b를 return 합니다.
a | b | result |
---|---|---|
9 | 91 | 991 |
89 | 8 | 898 |
const solution = (a, b) => {
let nums = [];
const strA = a + '';
const strB = b + '';
nums.push(strA + strB);
nums.push(strB + strA);
return nums[0] > nums[1] ? parseInt(nums[0]) : nums[0] === nums[1]? parseInt(nums[0]) : parseInt(nums[1])
}
function solution(a, b) {
return Math.max(Number(`${a}${b}`), Number(`${b}${a}`))
}
💡
Math.max()
로 쉽게 비교하기 !
단, a ⊕ b와 b ⊕ a가 같다면 a ⊕ b를 return 합니다. 이 조건은 '값'은 결국 동일하기 때문에 복잡하게 할 필요 없었다...