Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite52c206

Browse files
authored
Create 2864-maximum-odd-binary-number.kt
1 parent51c1363 commite52c206

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// traverse and swap indices
2+
classSolution {
3+
funmaximumOddBinaryNumber(s:String):String {
4+
val sArr= s.toCharArray()
5+
var left=0
6+
7+
for (iin0 until sArr.size) {
8+
if (sArr[i]=='1') {
9+
sArr[i]= sArr[left].also { sArr[left]= sArr[i] }
10+
left++
11+
}
12+
}
13+
14+
sArr[left-1]= sArr[sArr.lastIndex].also { sArr[sArr.lastIndex]= sArr[left-1] }
15+
return sArr.joinToString("")
16+
}
17+
}
18+
19+
// Count 1's and build at once
20+
classSolution {
21+
funmaximumOddBinaryNumber(s:String):String {
22+
var count=0
23+
for (cin s) {
24+
if (c=='1') count++
25+
}
26+
27+
return"1".repeat(count-1)+"0".repeat(s.length- count)+"1"
28+
}
29+
}
30+
31+
// Rolling string builder
32+
classSolution {
33+
funmaximumOddBinaryNumber(s:String)= buildString {
34+
var count= s.count { it=='1' }-1
35+
val n= s.length
36+
37+
for (iin0 until n-1) {
38+
if (count>0) {
39+
append("1")
40+
count--
41+
}else {
42+
append("0")
43+
}
44+
}
45+
46+
append("1")
47+
return toString()
48+
}
49+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp