๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Kotlin/Programmers Algorithm

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์ฝ”ํ‹€๋ฆฐ] ๋‚˜๋จธ์ง€๊ฐ€ 1์ด ๋˜๋Š” ์ˆ˜ ์ฐพ๊ธฐ #87389

by eun.24k 2023. 10. 20.

#87389

๐ŸŽ„ Question ?

class Solution {
    fun solution(n: Int): Int {
        var answer: Int = 0
        return answer
    }
}

 

๐Ÿงฉ Thought Process

  1. x๋ผ๋Š” ๋ฏธ์ง€์ˆ˜๋ฅผ 1์—์„œ๋ถ€ํ„ฐ ์ฐจ๊ทผ์ฐจ๊ทผ ๋Š˜๋ ค๋‚˜๊ฐ€๊ธฐ (for๋ฌธ ์‚ฌ์šฉ)
  2. n์„ x๋กœ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ ๋‚˜๋จธ์ง€๊ฐ€ 1์ธ์ง€ ํ™•์ธํ•˜๊ธฐ (if๋ฌธ ์‚ฌ์šฉ)
  3. ํ™•์ธํ–ˆ์„ ์‹œ ๋งž์œผ๋ฉด break

 

๐ŸŽ€ Answer

class Solution {
    fun solution(n: Int): Int {
        var answer: Int = 0
        for (x in 1 until n+1) {
            if (n % x == 1) {
                answer = x
                break
            }
        }
        return answer
    }
}

 

๐ŸŽ Result

 

๐Ÿ† Comment

์ดˆ๋ฐ˜ ์‰ฌ์šด ๋ฌธ์ œ๋“ค์ด ์‘ฅ์‘ฅ ํ’€๋ฆฌ๋‹ค๊ฐ€ ์ž๋ฆฟ์ˆ˜ ๋ฌธ์ œ์—์„œ ๋‚ด๊ฐ€ ์ƒ๊ฐํ•œ ๋ฐฉ๋ฒ•๋Œ€๋กœ ํ’€์–ด๋ณด๋ ค๊ณ  ๊ณ ์ง‘๋ถ€๋ฆฌ๋ฉด์„œ ์‹œ๊ฐ„ ์†Œ๋ชจ๋ฅผ ๋งŽ์ด ํ•ด์„œ์ธ์ง€ ๋ฌธ์ œ๊ฐ€ ๋ฐ”๋กœ ํ’€๋ ธ์„ ๋•Œ ์พŒ๊ฐ์ด ์•„์ฃผ ์ข‹๋‹น :))