자릿수의 합

minho·2021년 9월 8일
0

code

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));

알게된 점

1. Number.toString

#숫자를 문자열로 변환(number to string)
1. (숫자).toString()

(111).toString() // "111"
(NaN).toString() // "NaN"

  1. String(숫자)
    String 생성자 함수를 new 없이 활용하는 방법

    (111).toString() // "111"
    (NaN).toString() // "NaN"

  2. 숫자+""
    : 문자열 연결 연산자(+) 활용하는 방법. 따옴표로 감싼 빈 문자열을 더해주면 형변환이 발생한다.

    111 + "" // "111"
    NaN + "" // "NaN"

2. map과 reduce

2. map

#형식: 배열.map((요소, 인덱스, 배열) => { return 요소 });
#반복문을 돌며 배열 안의 요소들을 1대1로 짝지어 준다.
어떻게 짝지어줄 것인가 정의한 함수를 메서드의 인자로 넣어주면 된다.

const number = [1, 2, 3];
let result = number.map((v) => {
return v + 1;
});
result; // [2, 3, 4]

위에서 v = 1, 2, 3을 순회한다.

map 활용

const number = [1, 2, 3]
let result = number.map((v) => {
console.log(v % 2 ? '홀' : "짝");
});
console.log(result); // '홀',"짝",'홀'

3. reduce

#형식: 배열.reduce((누적값, 현잿값, 인덱스, 요소) => { return 결과 }, 초깃값);
이전값이 아니라 누적값에 주의!!!!

  • 덧셈 예시

    const number = [1, 2, 3];
    result = number.reduce((acc, cur, i) => {
    console.log(acc, cur i);
    return acc + cur;
    }, 0);
    // 0 1 0
    // 1 2 1
    // 3 3 2
    result; //6

    초기값을 적어주지 않으면 자동으로 acc의 번호는 0부터 시작함

reduce 활용

result = number.reduce((acc, cur) => {
acc.push(cur % 2 ? '홀수' : '짝수');
return acc;
}, []);
result; // ['홀수', '짝수', '홀수']

문제에서의 reduce 활용

let sum=x.toString().split('').reduce((a, b)=>a+Number(b), 0);

a(acc)의 값을 0으로 초기화 한다음 String인 b를 Number로 변환후 다시 a에 +하여 누적시킨다.

profile
Live the way you think

0개의 댓글