๋ฌธ์ œ

์–ด๋–ค ์ •์ˆ˜๋“ค์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ์ •์ˆ˜๋“ค์˜ ์ ˆ๋Œ“๊ฐ’์„ ์ฐจ๋ก€๋Œ€๋กœ ๋‹ด์€ ์ •์ˆ˜ ๋ฐฐ์—ด absolutes์™€ ์ด ์ •์ˆ˜๋“ค์˜ ๋ถ€ํ˜ธ๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ๋‹ด์€ ๋ถˆ๋ฆฌ์–ธ ๋ฐฐ์—ด signs๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ์‹ค์ œ ์ •์ˆ˜๋“ค์˜ ํ•ฉ์„ ๊ตฌํ•˜์—ฌ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋”ฉํ…Œ์ŠคํŠธ

 

์‚ฌ์šฉํ•œ ํ•จ์ˆ˜ 

์ค‘์ฒฉ if๋ฌธ :  absolutes์˜ ๋ฆฌ์ŠคํŠธ ์ˆœ์„œ์™€ signs์˜ ์ˆœ์„œ๋ฅผ ๊ฐ™๊ฒŒ ํ•˜๊ธฐ์œ„ํ•ด ์‚ฌ์šฉํ•˜์˜€๋‹ค.

 

 

ํ•ด๊ฒฐ

function solution(absolutes, signs) {
    var answer = 0;
    len = absolutes.length
    
    for (let i=0; i<len; i++)
        if (absolutes[i]) {
            if (signs[i] == true) {
                answer += absolutes[i]
            }else{
                answer -= absolutes[i]
            }             
        }
    
    return answer;
}

 

 

ํ•ด๊ฒฐ (๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ํ’€์ด ์ฐธ๊ณ )

function solution(absolutes, signs) {

    return absolutes.reduce((acc, val, i) => acc + (val * (signs[i] ? 1 : -1)), 0);
}

์‚ฌ์šฉํ•œ ํ•จ์ˆ˜: reduce()

 

 

 

ํ•ด๊ฒฐ(๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ํ’€์ด ์ฐธ๊ณ )

function solution(absolutes, signs) {
    let answer = 0;
    absolutes.forEach((v, i) => {
        if (signs[i]) {
            answer += v;
        } else {
            answer -= v;
        }
    })
    return answer;
}

์‚ฌ์šฉํ•œ ํ•จ์ˆ˜: forEach()

 

 

 

 

ํ•ด๊ฒฐ(๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ํ’€์ด ์ฐธ๊ณ )

function solution(absolutes, signs) {
    let answer = 0;
    for (let i = 0; i < absolutes.length; i++) {
        signs[i] ? answer += absolutes[i] : answer -= absolutes[i]
    }
    return answer;
}

์ฒ˜์Œ ๋ณด๋Š” ํ‘œํ˜„๋ฐฉ์‹์ด๋ผ ๊ฐ€์ ธ์™”๋‹ค.

 

 

 

๋ฌธ์ œ

๋ฌธ์ž์—ด s๋ฅผ ์ˆซ์ž๋กœ ๋ณ€ํ™˜ํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•˜์„ธ์š”.

์˜ˆ๋ฅผ๋“ค์–ด str์ด "1234"์ด๋ฉด 1234๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ , "-1234"์ด๋ฉด -1234๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.
str์€ ๋ถ€ํ˜ธ(+,-)์™€ ์ˆซ์ž๋กœ๋งŒ ๊ตฌ์„ฑ๋˜์–ด ์žˆ๊ณ , ์ž˜๋ชป๋œ ๊ฐ’์ด ์ž…๋ ฅ๋˜๋Š” ๊ฒฝ์šฐ๋Š” ์—†์Šต๋‹ˆ๋‹ค.

 

์‚ฌ์šฉํ•œ ํ•จ์ˆ˜ 

Number() : ๊ด„ํ˜ธ์— ํ•ด๋‹นํ•˜๋Š” ๋ณ€์ˆ˜๋ฅผ ์ˆซ์ž๋กœ ๋ฐ˜ํ™˜

 

ํ•ด๊ฒฐ

function solution(s) {
    var answer = 0;
    answer = Number(s)
    return answer;
}

 

ํ•ด๊ฒฐ (ํŒ€์› ์ฐธ๊ณ )

function solution(s) {
	var answer = parseInt(s);
    return answer;
}

์‚ฌ์šฉํ•œ ํ•จ์ˆ˜ :

perseIns() : ๊ด„ํ˜ธ์— ํ•ด๋‹นํ•˜๋Š” ๋ณ€์ˆ˜๋ฅผ ์ˆซ์ž๋กœ ๋ณ€ํ™˜

๋ฌธ์ œ

๋‘ ์ •์ˆ˜ a, b๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ a์™€ b์‚ฌ์ด์— ์†ํ•œ ๋ชจ๋“  ์ •์ˆ˜์˜ ํ•ฉ์„ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•˜์„ธ์š”.
์˜ˆ๋ฅผ ๋“ค์–ด a = 3, b=5์ธ ๊ฒฝ์šฐ, 3+4+5 = 12 ์ด๋ฏ€๋กœ 12๋ฅผ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค. 

 

์ž…์ถœ๋ ฅ ์˜ˆ

a b return
3 5 12
3 3 3
5 3 12

 

์‚ฌ์šฉํ•œ ํ•จ์ˆ˜ 

Math.min() : ๊ด„ํ˜ธ์˜ ๊ฐ’ ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ๋‚˜ํƒ€๋‚ธ๋‹ค.

Math.max() : ๊ด„ํ˜ธ์˜ ๊ฐ’ ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ๋‚˜ํƒ€๋‚ธ๋‹ค.

 

ํ•ด๊ฒฐ

function solution(a, b) {
    var answer = 0;
    
    min = Math.min(a,b)
    max = Math.max(a,b)

    for (let i=min; i <= max; i++) {
      
        answer += i        
    }    
    return answer;
}

 

+ Recent posts