개인공부/알고리즘
프로그래머스 - 다음에 올 숫자 (Kotlin)
KEEMSY
2023. 7. 23. 20:35
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
내가 생각한 문제의 핵심은, 주어진 common 이 등차수열인지, 등비수열인지 판별하는것이 핵심이라고 생각했다.
- isArithmeticSequence() 를 추가하여, 주어진 common 이 등차수열인지 확인하는 메서드를 작성했다.
- 해당 메서드에 따른 올바른 처리 로직을 작성하였다.
class Solution {
fun solution(common: IntArray): Int {
var answer = 0
val lastElement = common[common.size - 1]
if (isArithmeticSequence(common)) {
val commonDifference = common[1] - common[0]
answer = lastElement + commonDifference
} else {
val commonRatio = common[1] / common[0]
answer = lastElement * commonRatio
}
return answer
}
private fun isArithmeticSequence(sequence: IntArray): Boolean {
val commonDifference = sequence[1] - sequence[0]
for (i in 1 until sequence.size) {
if (sequence[i] - sequence[i - 1] != commonDifference) {
return false
}
}
return true
}
}
728x90