알고리즘

1번 문제

nozee 2020. 3. 14. 11:23
반응형

정수 배열과 정수 k가 주어지면 모든 원소를 k칸씩 앞으로 옮기시오.

 

Given an array and an integer K, shift all elements in the array K times.

 

input: [1, 2, 3, 4, 5], k = 2

output: [3, 4, 5, 1, 2]

 

input: [0, 1, 2, 3, 4], k = 1

output: [1, 2, 3, 4, 0]

 

 

import java.util.Scanner;
import javax.swing.plaf.synth.SynthScrollBarUI;
public class TestCode
{
   public static void main (String args[]){
       Scanner sc = new Scanner(System.in);
      
       int array[] = new int[5];
      
       System.out.println("배열을 입력해 주세요 : ");
      
       for(int b = 0 ; b< 5 ; b++) {
          array[b] = (int) sc.nextInt();
       }
      
       System.out.println("바뀔 횟수를 입력해주세요 : ");
       int k = sc.nextInt();
      
       for(int i = 0; i <k ; i++){
          int a = array[0];
          for(int j = 0; j < array.length-1 ; j++){
             array[j] = array[j+1];
             if(j == array.length-2){
                 array[j+1] = a;
             }
          }
       }
      
       for(int a = 0 ; a< 5; a++) {
          if(a<4) {
                 System.out.print(array[a] + ", ");
           }else {
                 System.out.print(array[a]);
           }
       }
      
   }
}

 

반응형