Blog

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

문제 #

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

  • 제한사항
    • n은 10,000,000,000이하인 자연수입니다.
  • 입출력 예
    n return
    12345 [5,4,3,2,1]

나의 풀이 #

class Solution {
    public int[] solution(long n) {
        String num = String.valueOf(n);
        int[] answer = new int[num.length()];
        
        for(int i = 0; i<num.length(); i++) {
            answer[i] = num.charAt(num.length()-i-1) - '0';
        }
        
        return answer;
    }
}
class Solution {
    public int[] solution(long n) {
        String num = String.valueOf(n);
        int[] answer = new int[num.length()];
        
        for(int i=num.length(); i>0; i--) {
            answer[num.length()-i] = num.charAt(i-1) - '0';
        }
        
        return answer;
    }
}

다른 사람의 풀이 #

class Solution {
  public int[] solution(long n) {
      String a = "" + n;
        int[] answer = new int[a.length()];
        int cnt=0;

        while(n>0) {
            answer[cnt]=(int)(n%10);
            n/=10;
            System.out.println(n);
            cnt++;
        }
      return answer;
  }
}

관련개념 학습 #