ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 연속된 수의 합
    코딩 테스트/Level 0 2022. 11. 8. 16:24
    반응형

    https://school.programmers.co.kr/learn/courses/30/lessons/120923

    파이썬

    num이 홀수일 때, total // num이 가운데 숫자가 되니 쉽게 찾을 수 있고, 
    num이 짝수일 때는 약간의 변형이 필요하다.  

    def solution(num, total):
        a, b = divmod(total, num)
        temp = (num - 1) // 2
        return [each for each in range(a - temp, a + temp + 1 + (0 if b == 0 else 1))]

    수학적으로 접근하면 더 좋다. 

    def solution(num, total):
        start = total // num - (num - 1) // 2
        return [each for each in range(start, start + num)]
    def solution(num, total):
        return list(range(total // num - (num - 1) // 2, total // num - (num - 1) // 2 + num))

    코틀린

    class Solution {
        fun solution(num: Int, total: Int): IntArray {
            val numbers = IntArray(num)
            val start = total / num - (num - 1) / 2
            for (i in 0 until num) {
                numbers[i] = start + i
            }
            return numbers
        }
    }

    코틀린에서 범위를 이용하여 IntArray를 초기화 하는 방법은 다음과 같다. 

    val array = IntArray(10) { it + 1 }

    이를 이용하면.. 

    class Solution {
        fun solution(num: Int, total: Int) = IntArray(num) { it + total / num - (num - 1) / 2 }
    }
    반응형
Designed by Tistory.