Coding Test/[프로그래머스] Java

[프로그래머스 / Java] Lv.1 푸드 파이트 대회

annovation 2025. 5. 1. 17:01

Question

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


Code

💡방법 1

class Solution {
    public String solution(int[] food) {
        String answer = "0";

        for (int i = food.length - 1; i > 0; i--) {
            for (int j = 0; j < food[i] / 2; j++) {
                answer = i + answer + i; 
            }
        }

        return answer;
    }
}
  • String + int는 결과가 String타입이다. [각주:1]

💡방법 2

class Solution {
    public String solution(int[] food) {
        StringBuilder sb = new StringBuilder();
        
        for(int i = 1; i < food.length; i++) {
            int count = food[i] / 2;
            sb.append(String.valueOf(i).repeat(count));
        }
        
        String answer = sb + "0";
        answer += sb.reverse();
        
        return answer;
    }
}
  • String.repeat(int count) [각주:2]
    • 현재 문자열을 count번 반복한 새 문자열 반환