자릿수의 합

frenchkebab·2021년 8월 20일
0
post-thumbnail



2가지 풀이


방법1) string 내장 메소드 사용

(내가 푼 방식이다)

      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() 메소드가 있는 줄도 몰랐음)


방법2) 10씩 나누는 방식

(원래 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()을 해 주어야 한다는 점!

profile
Blockchain Dev Journey

0개의 댓글