이 문제의 핵심은 크게 아래와 같이 볼 수 있다.
- 10진수를 2진수로 변환
- '1'을 '#'으로, '0'을 공백으로 치환
처음엔 자바에서 지원하는 함수를 쓸 생각을 전혀 못해서 2진수로 변환하는 함수를 직접 구현했다.
채점 결과 정답은 맞췄으나 실행 속도가 너무 느려서 (당연함) 다른방식으로도 풀어보았다.
class Solution {
public static String binary(int num, int n) {
String str = "";
// 2진수로 변환
while(true) {
if(num < 2) {
str = num + str;
break;
}
str = (num % 2) + str;
num /= 2;
}
// 자릿수 맞추기
if(str.length() != n) {
String temp = "0";
int r = n - str.length();
temp = temp.repeat(r);
str = temp + str;
}
return str;
}
public String[] solution(int n, int[] arr1, int[] arr2) {
String[] answer = new String[n];
for(int i = 0; i < n; i++) {
String str1 = binary(arr1[i], n);
String str2 = binary(arr2[i], n);
String temp = "";
for(int j = 0; j < n; j++) {
int c1 = str1.charAt(j) - '0';
int c2 = str2.charAt(j) - '0';
// '1'을 '#'으로, '0'을 공백으로 치환
if(c1 != c2) {
temp += "#";
} else {
if(c1 == 0) temp += " ";
else temp += "#";
}
}
answer[i] = temp;
}
return answer;
}
}
Java에서 지원하는 Integer.toBinaryString()
replace()
함수와 비트 OR 연산자
를 사용하여 풀어보니 코드도 훨씬 깔끔하고 시간도 엄청 빨라진 걸 확인할 수 있다.
class Solution {
public String[] solution(int n, int[] arr1, int[] arr2) {
String[] answer = new String[n];
String str;
for(int i = 0; i < n; i++) {
// 10진법으로 이진형태의 문자열로 반환
str = Integer.toBinaryString(arr1[i] | arr2[i]); // 비트 OR 연산자
// 자릿수 맞추기
if(str.length() != n) {
str = "0".repeat(n - str.length()) + str;
}
// '1'을 '#'으로, '0'을 공백으로 치환
str = str.replace("1", "#");
str = str.replace("0", " ");
answer[i] = str;
}
return answer;
}
}