Skip to content

Commit 808b39e

Browse files
authored
Create 1703-maximum-binary-string-after-change.js
1 parent 5a02b7c commit 808b39e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {string} binary
3+
* @return {string}
4+
*/
5+
const maximumBinaryString = function(binary) {
6+
let n = binary.length;
7+
const {max} = Math
8+
let nums = [];
9+
for (let i = 0; i < n; ++i) {
10+
nums.push(+binary[i]);
11+
}
12+
for (let i = 0, j = 0; i < n - 1; ++i) {
13+
if (nums[i] == 1) continue;
14+
if (nums[i + 1] == 0) {
15+
nums[i] = 1;
16+
continue;
17+
}
18+
j = max(j, i + 1);
19+
while (j < n && nums[j]) ++j;
20+
if (j === n) break;
21+
nums[j++] = 1;
22+
nums[i + 1] = 0;
23+
nums[i] = 1;
24+
}
25+
let res = "";
26+
for (let i = 0; i < n; ++i) {
27+
res += (nums[i] + '');
28+
}
29+
return res;
30+
};

0 commit comments

Comments
 (0)