ABOUT ME

-

오늘 방문자
-
어제 방문자
-
전체
-
  • [programmers] 자연수 뒤집어 배열로 만들기
    알고리즘 2019. 12. 4. 23:52


    접근방법


    1. 일단 각 숫자를 배열로 만들려고함.

    2. 문자열로 변환시킨뒤

    3. split을 이용해 쪼갬

    4. 반복문과 카운트 변수를 이용해 결과값을 만듬


    처음에는 StringBuffer class의 revers()메소드로 편하게 하려했으나, 구현체를 보니 복잡도나 메모리측면에서 좋지않은 것으로 판단.

    for문을 돌때 결과값을 역으로 넣기로 함




    package com.cm;

    /**
    * 문제 : 자연수 뒤집어 배열로 만들기
    * https://programmers.co.kr/learn/courses/30/lessons/12932
    *
    * 문제 설명
    * 자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.
    *
    * 제한 조건
    * n은 10,000,000,000이하인 자연수입니다.
    * 입출력 예
    * n return
    * 12345 [5,4,3,2,1]
    */
    public class 자연수_뒤집어_배열로_만들기 {

    public 자연수_뒤집어_배열로_만들기(){
    long n =12345;
    System.out.println(solution(n));
    }

    public int[] solution(long n) {
    String str = String.valueOf(n);

    String[] arr = str.split("");

    int[] answer = new int[arr.length];

    int j = 0;
    for(int i =arr.length-1 ; i>=0; i--){
    answer[j] = Integer.parseInt(arr[i]);
    j++;
    }

    // for(int i : answer) System.out.println(i);

    return answer;
    }
    }




    참고


    StringBuffer의 revers메소드 로직

    /**
    * Causes this character sequence to be replaced by the reverse of
    * the sequence. If there are any surrogate pairs included in the
    * sequence, these are treated as single characters for the
    * reverse operation. Thus, the order of the high-low surrogates
    * is never reversed.
    *
    * Let <i>n</i> be the character length of this character sequence
    * (not the length in {@code char} values) just prior to
    * execution of the {@code reverse} method. Then the
    * character at index <i>k</i> in the new character sequence is
    * equal to the character at index <i>n-k-1</i> in the old
    * character sequence.
    *
    * <p>Note that the reverse operation may result in producing
    * surrogate pairs that were unpaired low-surrogates and
    * high-surrogates before the operation. For example, reversing
    * "\u005CuDC00\u005CuD800" produces "\u005CuD800\u005CuDC00" which is
    * a valid surrogate pair.
    *
    * @return a reference to this object.
    */
    public AbstractStringBuilder reverse() {
    boolean hasSurrogates = false;
    int n = count - 1;
    for (int j = (n-1) >> 1; j >= 0; j--) {
    int k = n - j;
    char cj = value[j];
    char ck = value[k];
    value[j] = ck;
    value[k] = cj;
    if (Character.isSurrogate(cj) ||
    Character.isSurrogate(ck)) {
    hasSurrogates = true;
    }
    }
    if (hasSurrogates) {
    reverseAllValidSurrogatePairs();
    }
    return this;
    }


    '알고리즘' 카테고리의 다른 글

    [hackerRank] AngryProfessor  (0) 2019.12.17
    [hackerRank] DiagonalDifference  (0) 2019.12.10
    [programmers] 제일 작은 수 제거하기  (0) 2019.12.03
    [Codility] PassingCars 70→100  (0) 2019.05.06
    [Codility]MaxCounters  (1) 2019.05.06

    댓글

Designed by Tistory.