๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 1๋‹จ๊ณ„ : ๋‘ ์ •์ˆ˜ ์‚ฌ์ด์˜ ํ•ฉ

by _ํ† ๋งคํ†  2022. 11. 14.
728x90

๐Ÿ–ฑ ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 1๋‹จ๊ณ„ : ๋‘ ์ •์ˆ˜ ์‚ฌ์ด์˜ ํ•ฉ ๐Ÿ–ฑ


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

์ œํ•œ ์‚ฌํ•ญ : a์™€ b๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” ๋‘˜ ์ค‘ ์•„๋ฌด ์ˆ˜๋‚˜ ๋ฆฌํ„ดํ•˜์„ธ์š”.
a์™€ b๋Š” -10,000,000 ์ด์ƒ 10,000,000 ์ดํ•˜์ธ ์ •์ˆ˜์ž…๋‹ˆ๋‹ค.
a์™€ b์˜ ๋Œ€์†Œ๊ด€๊ณ„๋Š” ์ •ํ•ด์ ธ์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

function solution(a, b) {
        let answer = a;
        while(a != b){
            (a < b) ? a++ : a-- ;
            answer = answer + a;
        }
        return answer;
    }
    

while๋ฌธ์œผ๋กœ num๊ณผ b ๊ฐ’์ด ๊ฐ™์ง€ ์•Š์„ ๊ฒฝ์šฐ ๊ณ„์† ๋ฐ˜๋ณตํ•˜๊ณ  ๊ฐ™์„ ๊ฒฝ์šฐ ๋ฐ˜๋ณต์„ ๋ฉˆ์ถ”๋„๋ก ์„ค์ •ํ–ˆ์Šต๋‹ˆ๋‹ค.
์กฐ๊ฑด์‚ผํ•ญ์ž๋ฅผ ํ†ตํ•ด a์™€ b๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ a ๊ฐ’์— +1 ๋˜๋Š” -1๋˜๋„๋ก ํ•˜์˜€์Šต๋‹ˆ๋‹ค.


#2. ๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ํ’€์ด

function adder(a, b){
        var result = 0
        //ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•˜์„ธ์š”
    
    
        return (a+b)*(Math.abs(b-a)+1)/2;
    }
    

์—ญ์‹œ... ์ˆ˜ํ•™์„ ์ž˜ ํ•ด์•ผํ•˜๋‚˜ ๋ด…๋‹ˆ๋‹ค.. ๊ณ„์‚ฐ์‹์œผ๋กœ ํ•œ๋ฒˆ์— ๋ฆฌํ„ดํ•ด์ฃผ์—ˆ๋„ค์š”.... ์ฆ‰ ์–‘ ๋์˜ ํ•ฉ * ์–‘ ๋์˜ ํ•ฉ์˜ ๊ฐœ์ˆ˜๋ผ๊ณ  ๋ณด๋ฉด ๋  ๋“ฏ ํ•ฉ๋‹ˆ๋‹ค... ใ…Žใ„ทใ„ท;;;

728x90

๋Œ“๊ธ€


Lucky Charms Rainbow
js
html
css