[프로그래머스] Level1. 2018 KAKAO BLIND RECRUITMENT - [1차] 비밀지도

Benjamin·2023년 3월 20일
0

프로그래머스

목록 보기
50/58


Troubleshooting

먼저 10진수를 2진수로 바꾸는 메소드는 아는데, 이걸 처음에는 byte 타입 배열에 저장해야하나?하고 잘 못 생각했다.

Integer.toString()을 사용해서 10진수를 n진수로 바꿀 수 있는데, 반환값의 타입은 String이다.

문제

하지만 이렇게했을 때 문제가 생겼다.
맨 앞이 0이면 지워진다는것이다.

해결

배열 각 원소의 길이가 n이 될때까지 앞에 0을 붙였다.

for(int i=0; i<n; i++) {
    while(temp1[i].length() < n){
        temp1[i] = '0' + temp1[i]; 
    }
    while(temp2[i].length() < n){
        temp2[i] = '0' + temp2[i]; 
    }
}

제출코드

import java.util.Arrays;
class Solution {
    public String[] solution(int n, int[] arr1, int[] arr2) {
        String[] answer = new String[n];
        Arrays.fill(answer, "");
        String[] temp1 = new String[n];
        String[] temp2 = new String[n];
        for(int i=0; i<n; i++) {
            temp1[i] = Integer.toString(arr1[i],2);
            temp2[i] = Integer.toString(arr2[i],2);
        }
        for(int i=0; i<n; i++) {
            while(temp1[i].length() < n){
                temp1[i] = '0' + temp1[i]; 
            }
            while(temp2[i].length() < n){
                temp2[i] = '0' + temp2[i]; 
            }
        }
        for(int i=0; i<n; i++) {
            for(int k=0; k<n; k++) {
                if(temp1[i].charAt(k) == '1' || temp2[i].charAt(k) == '1') answer[i] += '#';
                else answer[i] += ' ';
            }
        }
        return answer;
    }
}

반복문이 너무 많은 느낌...

다른 풀이

class Solution {
  public String[] solution(int n, int[] arr1, int[] arr2) {
        String[] result = new String[n];
        for (int i = 0; i < n; i++) {
            result[i] = Integer.toBinaryString(arr1[i] | arr2[i]);
        }

        for (int i = 0; i < n; i++) {
            result[i] = String.format("%" + n + "s", result[i]);
            result[i] = result[i].replaceAll("1", "#");
            result[i] = result[i].replaceAll("0", " ");
        }

        return result;
    }
}
  • bit 연산자의 논리 연산자 |을 써서 결과배열은 하나만 생성했다.
    (| : 둘 중 하나라도 1이 있으면 결과는 1)

  • String.format("%" + n + "s", result[i]);을 사용해서 연산결과의 길이가 맞지않는것은 공백으로 채웠다.
    -> 처음에 이 부분이 이해가 안갔다. 0으로 채워야하지않나?생각했는데, 어쨌든 0을 공백으로 변환해서 출력할것이기때문에 상관없다.


After가 없는것은 코드를 사용하기 전이고(길이 변환 전), After가 앞에 붙은것은 코드가 돌아간 후(길이 변환 후)이다. 부족한 길이만큼 앞에 공백이 붙은것을 볼 수 있다.

  • replaceAll()을 사용해서 출력해야하는 문자로 변환한다!

공부한 사항

  • String.format()

0개의 댓글