👩‍💻 코테 공부/코테 공부

[코테 - Java] 프로그래머스 - 자연수 뒤집어 배열로 만들기

수댕ʕت̫͡ʔ 2024. 9. 11. 16:37

https://school.programmers.co.kr/learn/courses/30/lessons/12932

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

1. 문제

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

2. 내가 푼 답안

1) Solution

import java.util.*;

class Solution {
    public int[] solution(long n) {
        ArrayList<Integer> list = new ArrayList<>();
        
        String temp = String.valueOf(n);
        
        for (int i = temp.length()-1; i >= 0 ; i--) {
            list.add(Character.getNumericValue(temp.charAt(i)));
        }
        
        int[] answer = new int[list.size()];
        for (int i = 0; i <list.size(); i++) {
            answer[i] = list.get(i);
        }
        
        return answer;
    }
}

2) Solution

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

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

3. 시간복잡도

O(n)

4. 문법 정리

1. JAVA 자료구조

리스트 List 선언

import java.util.*

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);

 

이중 리스트 선언

import java.util.*;

List<List<Integer>> list = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
temp.add(1);
temp.add(2);
list.add(temp);

 

데큐(Deque) 선언

import java.util.*;

Deque<Integer> deque = new ArrayDeque<>();
deque.addFirst(1);
deque.addLast(2);

int first = deque.removeFirst();
int last = deque.removeLast();

 

딕셔너리 선언

import java.util.*;

Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);
int value = map.get("apple");