본문 바로가기
프로그래머스/[프로그래머스 - JAVA] Lv.1

[프로그래머스 - JAVA] 자연수 뒤집어 배열로 반들기

by 코딩하는 흰둥이 2023. 3. 26.
반응형


  • 내 풀이
import java.util.*;

class Solution {
    public int[] solution(long n) {
        int[] answer = {};
        
        String[] change = String.valueOf(n).split("");

        List<String> check = new ArrayList<>(Arrays.stream(change).toList());

        Collections.reverse(check);

        answer = new int[check.size()];

        for (int i = 0; i < check.size(); i++) {
            answer[i] = Integer.parseInt(check.get(i));
        }
        return answer;
    }
}

IntelliJ에서 멀쩡히 돌아가는 코드가 프로그래머스에서 오류가 난다...

코드 변경...

class Solution {
    public int[] solution(long n) {
        int[] answer = {};
        
        // answer 초기화 시킬 값
        int count = 0;
        
        // while 반복하기 위한 값
        long check = n;
        
        while(check > 0){
        // 나머지를 계속 잘라 나가는 방식
            check = check/10;
            count++;
        }

        answer = new int[count];
		
        for (int i = 0; i < count; i++) {
        // n이 long 타입이기때문에 int로 형변환을 해야한다
        // (int)n%10은 테스트 실패가 뜨기 때문에 계산을 다한 상태에서 (int)가 되어야 한다
            answer[i] = (int)(n%10);
            n = n/10;
        }
        
        return answer;
    }
}

 

  • 다름 사람 풀이
import java.util.stream.IntStream;

class Solution {
    public int[] solution(long n) {
        return new StringBuilder().append(n).reverse().chars().map(Character::getNumericValue).toArray();
    }
}





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;
  }
}

댓글