티스토리 뷰

반응형

Using Language : Java
Using Tool : Eclipse


  • 프로그래머스 문제 소개

< 자연수 뒤집어 배열로 만들기 >

문제 설명

자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.

제한 조건

  • n은 10,000,000,000이하인 자연수입니다.

예시

	n 		return 
	12345 	[5,4,3,2,1]

의사코드

  1. n의 길이를 구해서 for문 돌리기
  2. n을 10으로 나누어서 나머지값 배열에 넣어주기
    • 자릿수 구하기에서 쓴 방법과 동일하다!
    • input 타입이 long 형이므로, 연산할때 int형으로 변형해서 해주어야한다!

long형인걸 간과해서 왜 안되나 했다..

<Solution16.java>

package level1;

public class Solution16 {
	
	public int[] solution(long n) {
	      int len=Long.toString(n).length();
	      int[] answer = new int[len];
	      
	      for(int i=0;i<len;i++) {
	    	  answer[i]= (int)(n%10);
	    	  n/=10;
	      }
	      return answer;
	  }
}

<Solution16Test.java>

package level1;

import static org.junit.Assert.assertArrayEquals;

import org.junit.Test;

public class Solution16Test {
	@Test
	public void 결과() {
		Solution16 solution = new Solution16();
		int[] answer = { 5, 4, 3, 2, 1 };
		assertArrayEquals(answer, solution.solution(12345));

	}
}

 

github에서 코드 확인하기

 

udud0510/CodeKata

프로그래머스 문제풀이. Contribute to udud0510/CodeKata development by creating an account on GitHub.

github.com

 

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함