정답
class Solution {
public String[] solution(int n, int[] arr1, int[] arr2) {
String[] answer = new String[n];
/*
#는 하나라도 있으면 # - 1
" "는 둘 다 일치해야 " " - 0
*/
for(int i=0; i<n; i++){
String str1 = binaryString(arr1[i], n);
String str2 = binaryString(arr2[i], n);
String temp = "";
for(int j=0; j<n; j++){
char ch1 = str1.charAt(j);
char ch2 = str2.charAt(j);
if(ch1 == '0' && ch2 == '0'){
temp += " ";
}else{
temp += "#";
}
}
answer[i] = temp;
}
return answer;
}
private String binaryString(int num, int n){
String result = "";
if(num == 0){
for(int i=0; i<n; i++){
result += "0";
}
return result;
}
while(num != 0){
result = String.valueOf(num % 2) + result;
num /= 2;
}
if(result.length() < n){
int loop = n - result.length();
for(int i=0; i<loop; i++){
result = "0" + result;
}
}
return result;
}
}
분석
- 단순 이진변환 문제였다.
- 이진변환에서
result = String.valueOf(num % 2) + result;
이 부분의 String 더해지는 순서 때문에 오류가 발생했었다.
참고할 만한 정답
- 아래 정답에서
result[i] = Integer.toBinaryString(arr1[i] | arr2[i]);
이 부분이 참고할 만함.
- Integer.toBinaryString() 함수는 10진수를 2진수로 변환하는 함수이다.
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;
}
}