(내가 푼 방식이다)
function solution(n, arr) {
let answer,
max = Number.MIN_SAFE_INTEGER;
for (let x of arr) {
let sum = x
.toString()
.split('')
.reduce((a, b) => a + Number(b), 0);
if (sum > max) {
max = sum;
answer = x;
} else if (sum === max) {
if (x > answer) answer = x;
}
}
return answer;
}
let arr = [128, 460, 603, 40, 521, 137, 123];
console.log(solution(7, arr));
전반적으로 해설과 똑같이 풀었으나,
toString()
대신String()
을 사용하였다.
(toString()
메소드가 있는 줄도 몰랐음)
(원래 C++로 할 때 풀던 방식이다)
function solution(n, arr) {
let answer,
max = Number.MIN_SAFE_INTEGER;
for (let x of arr) {
let sum = 0,
tmp = x;
while (tmp) {
sum += tmp % 10;
tmp = Math.floor(tmp / 10);
}
if (sum > max) {
max = sum;
answer = x;
} else if (sum === max) {
if (x > answer) answer = x;
}
}
return answer;
}
let arr = [128, 460, 603, 40, 521, 137, 123];
console.log(solution(7, arr));
C++로 풀 때와 사뭇 다른 점은 10으로 나누었을 때 실수로 들어가서
Math.floor()
을 해 주어야 한다는 점!