728x90
<코딩 테스트>
문제 설명
등차수열 혹은 등비수열 common이 매개변수로 주어질 때, 마지막 원소 다음으로 올 숫자를 return 하도록 solution 함수를 완성해보세요.
<나의 풀이 과정>
등차수열 : 첫번째 값과 두번째 값의 차이가 두번째 값과 세번째 값의 차이가 같으면 등차,
그게 아니라면 두번째 값을 첫번째 값으로 나눈 값의 결과를 곱해주면 된다.
<나의 풀이 코드>
package com.programmers.level00.다음에올숫자;
//등차수열 혹은 등비수열 common이 매개변수로 주어질 때, 마지막 원소 다음으로 올 숫자를 return 하도록 solution 함수를 완성해보세요.
public class Test {
public static void main(String[] args) {
System.out.println(solution(new int[] { 1, 2, 3, 4 })); // 5
System.out.println(solution(new int[] { 2, 4, 8 }));// 16
}
static int solution(int[] common) {
//등차수열 : 첫번째 값과 두번째 값의 차이가 두번째 값과 세번째 값의 차이가 같으면 등차
// 그게 아니라면 두번째 값을 첫번째 값으로 나눈 값의 결과를 곱해주면 된다.
int answer = 0;
if ((common[1] - common[0])==(common[2] - common[1])) {
answer = common[common.length-1]+(common[1] - common[0]);
}else {
answer= common[common.length-1]*(common[1] / common[0]);
}
return answer;
}
}
<다른 사람 풀이>
class Solution {
public int solution(int[] common) {
int answer = 0;
int x = common[1] - common[0];
int y = common[2] - common[1];
if (x == y) {
answer = common[common.length - 1] + y;
} else {
answer = common[common.length - 1] * common[2] / common[1];
}
return answer;
}
}
<다른 사람 풀이>
class Solution {
public int solution(int[] common) {
boolean plusCheck = false;
//등차 등비 판단
int first = common[1]-common[0];
int second = common[2]-common[1];
if(first == second) plusCheck = true;
int answer = plusCheck ? common[common.length-1]+first : common[common.length-1]*(common[1]/common[0]);
return answer;
}
}
https://school.programmers.co.kr/learn/courses/30/lessons/120913
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
728x90
'주니어 기초 코딩공부 > JAVA_programmers_코딩테스트' 카테고리의 다른 글
구슬을 나누는 경우의 수_programmers_lev00 (0) | 2023.01.04 |
---|---|
연속된 수의 합_programmers_lev00 (0) | 2023.01.03 |
최빈값 구하기_programmers_lev00 (0) | 2023.01.01 |
OX퀴즈_programmers_lev00 (0) | 2023.01.01 |
직사각형 넓이 구하기_programmers_lev00 (0) | 2022.12.29 |