1980. Find Unique Binary String

Bit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public String findDifferentBinaryString(String[] nums) {
Arrays.sort(nums);

int bitCount = nums[0].length();
for (int i = 0; i < 2 << bitCount && i < nums.length; i++) {
String actualStr = nums[i];
int actualNum = 0;
for (int j = 0; j < actualStr.length(); j++) {
actualNum = actualNum * 2 + actualStr.charAt(j) - '0';
}
if (i != actualNum) {
return toBitString(i, bitCount);
}
}

return toBitString(nums.length, bitCount);
}

private String toBitString(int num, int bitCount) {
StringBuilder sb = new StringBuilder();
while (num != 0) {
sb.append(num % 2);
num /= 2;
}
while (sb.length() < bitCount) {
sb.append(0);
}
return sb.reverse().toString();
}
}

Math

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public String findDifferentBinaryString(String[] nums) {
int n = nums.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (nums[i].charAt(i) == '0') {
sb.append(1);
} else {
sb.append(0);
}
}
return sb.toString();
}
}

References

1980. Find Unique Binary String