let's get IT with DAVINA ๐Ÿ’ป

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค]Lv0. ์ œ๊ณฑ์ˆ˜ ํŒ๋ณ„ํ•˜๊ธฐ ๋ณธ๋ฌธ

DEV_IN/๋ฌธ์ œํ’€์ด

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค]Lv0. ์ œ๊ณฑ์ˆ˜ ํŒ๋ณ„ํ•˜๊ธฐ

๋‹ค๋นˆ์น˜์ฝ”๋“œ๐Ÿ’Ž 2023. 3. 22. 16:37

โ“๋ฌธ์ œ ์„ค๋ช…

์–ด๋–ค ์ž์—ฐ์ˆ˜๋ฅผ ์ œ๊ณฑํ–ˆ์„ ๋•Œ ๋‚˜์˜ค๋Š” ์ •์ˆ˜๋ฅผ ์ œ๊ณฑ์ˆ˜๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์ •์ˆ˜ n์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, n์ด ์ œ๊ณฑ์ˆ˜๋ผ๋ฉด 1์„ ์•„๋‹ˆ๋ผ๋ฉด 2๋ฅผ returnํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

๐Ÿšซ ์ œํ•œ์‚ฌํ•ญ

  • 1 ≤ n ≤ 1,000,000

โ—๏ธ ๋น„๋‹ˆ's ํ’€์ด

function solution(n) {
    if(Number.isInteger(Math.sqrt(n))===true){
        return 1;
    } else return 2;
}

๐Ÿ‘€ others' ํ’€์ด

function solution(n) {
    for (let i=0; i*i <= n; i++) {
        if (i*i === n) return 1
    }

    return 2;
}
function solution(n) {
    return Math.sqrt(n) % 1 === 0 ? 1 : 2;
}

⊕ Extra Knowledge ++

  • Math.sqrt(x)
    • x์˜ ์ œ๊ณฑ๊ทผ ๋ฐ˜ํ™˜
    • %1์„ ํ•ด์„œ ๋‚˜๋จธ์ง€๊ฐ€ 0์ด๋ฉด ์ œ๊ณฑ์ˆ˜ ๋งž์Œ
  • Number.isInteger(x)
    • x๊ฐ€ ์ •์ˆ˜์ธ์ง€ ํ™•์ธํ•˜๋ ค๊ณ  ํ•˜๋Š” ๋ฉ”์„œ๋“œ 
    • boolean return
Comments