[프로그래머스] 배열 회전시키기 - JAVA
2023. 4. 2. 19:34ㆍ프로그래머스 - JAVA
문제
정수가 담긴 배열 numbers와 문자열 direction가 매개변수로 주어집니다. 배열 numbers의 원소를 direction방향으로 한 칸씩 회전시킨 배열을 return하도록 solution 함수를 완성해주세요.
조건
3 ≤ numbers의 길이 ≤ 20
direction은 "left" 와 "right" 둘 중 하나입니다.
코드
class Solution {
public int[] solution(int[] numbers, String direction) {
int num = numbers.length;
int[] answer = new int[num];
if(direction.equals("left")){
int temp = numbers[0];
for(int i = 0;i<num;i++){
if(i==num-1){
answer[i] = temp;
break;
}
answer[i] = numbers[i+1];
}
}
else{
int temp = numbers[num-1];
for(int i = num-1; i>=0; i--){
if(i==0){
answer[i] = temp;
break;
}
answer[i] = numbers[i-1];
System.out.println("i = "+i );
}
}
return answer;
}
}
출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges
'프로그래머스 - JAVA' 카테고리의 다른 글
[프로그래머스] 숫자 찾기 - JAVA (0) | 2023.04.02 |
---|---|
[프로그래머스] 약수 구하기 - JAVA (0) | 2023.04.02 |
[프로그래머스] n의 배수 고르- JAVA (0) | 2023.04.02 |
[프로그래머스] 중복된 문자 제거 - JAVA (0) | 2023.04.02 |
[프로그래머스] 대문자와 소문자 - JAVA (0) | 2023.04.02 |