728x90

https://www.acmicpc.net/problem/2908

Code

https://github.com/DasolPark/Algorithm_JavaScript/blob/ebb4130f5a91e299f73bbe1e4e6d7986538d6e2b/Baekjoon/2908.js

😢 순서를 뒤바꾸는 방법으로 간단하게 푼 문제(Reverse Int or String Algorithm 참고)

😊 입력값으로 받은 숫자 StringArray로 나누고(split('')) reduce를 이용하여 순서를 뒤바꿔 줬다.
그런 후 각 세자리 숫자만큼 나눠서(split(' ')) 배열에 저장하고 Math.max.apply()를 이용해 더 큰 값을 구해줬다.
(아래 Full Code를 참고하면, reduce를 쓰지않고 다른 방법을 사용하여 푼 예제를 볼 수 있다)

✔ String.prototype.split('')

element 하나하나씩 나눠서 배열로 return해줬다. ( [ '7', '3', '4', ' ', '8', '9', '3' ] )

✔ Array.prototype.reduce()

안에 순서를 뒤바꾸는 reduce function을 주입하여 return해줬다. ( '398 437' )

✔ String.prototype.Split(' ')

가운데 공백(space)을 이용해 세자리 숫자씩 각각 나눠줬다. ( [ '734', '839' ] )

✔ Math.max.apply()

apply()에 숫자를 넣어서 max(더 큰)값을 구해줬다

위의 Skill들은 JavaScript - helper methods 카테고리에서 간단한 사용방법을 확인할 수 있다.

Full Code

// 2nd Solution(reduce(), Math.max.apply())
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
const input = '734 893';
const revEntire = input.split('').reduce((rev, numChar) => numChar + rev, '');
const eachNumArr = revEntire.split(' ');
const max = Math.max.apply(null, eachNumArr);
 
console.log(max);
 
// 1st Solution(reduce, Math.max.apply())
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = '734 893';
// const reverseInt = input
// .split('')
// .reduce((rev, num) => {
// return num + rev;
// }, '')
// .split(' ');
// const max = Math.max.apply(null, reverseInt);
 
// console.log(max);
 
// 3rd Solution(for...of, No Math.max())
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = '734 893';
// let rev = '';
 
// for (let numChar of input) {
// rev = numChar + rev;
// }
 
// const eachNumArr = rev.split(' ').map(num => parseInt(num));
// let max = 0;
 
// for (let i = 0; i < eachNumArr.length; i++) {
// if (eachNumArr[i] > max) {
// max = eachNumArr[i];
// }
// }
 
// console.log(max);
 
// 4th Solution(reverse())
 
// For submit
 
// const fs = require('fs');
// const input = fs.readFileSync('/dev/stdin').toString().trim();
 
// For local test
// const input = '734 893';
// let rev = input
// .split('')
// .reverse()
// .join('');
 
// const eachNumArr = rev.split(' ').map(num => parseInt(num));
// let max = 0;
 
// for (let i = 0; i < eachNumArr.length; i++) {
// if (eachNumArr[i] > max) {
// max = eachNumArr[i];
// }
// }
 
// console.log(max);

+ Recent posts