Skip to content

Commit 1bb6ea3

Browse files
committedJun 20, 2022
2022-06-20 update: added "Largest Number After Digit Swaps by Parity"
1 parent 63d4800 commit 1bb6ea3

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.smlnskgmail.jaman.leetcodejava.easy;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.List;
6+
7+
// https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/
8+
public class LargestNumberAfterDigitSwapsByParity {
9+
10+
private int input;
11+
12+
public LargestNumberAfterDigitSwapsByParity(int input) {
13+
this.input = input;
14+
}
15+
16+
public int solution() {
17+
List<Integer> odds = new ArrayList<>();
18+
List<Integer> evens = new ArrayList<>();
19+
int ref = input;
20+
while (input > 0) {
21+
int curr = input % 10;
22+
if (curr % 2 != 0) {
23+
odds.add(curr);
24+
} else {
25+
evens.add(curr);
26+
}
27+
input /= 10;
28+
}
29+
Collections.sort(odds);
30+
Collections.sort(evens);
31+
int pO = 0;
32+
int pE = 0;
33+
int result = 0;
34+
int mul = 1;
35+
while (ref > 0) {
36+
int curr = ref % 10;
37+
if (curr % 2 != 0) {
38+
result = odds.get(pO++) * mul + result;
39+
} else {
40+
result = evens.get(pE++) * mul + result;
41+
}
42+
ref /= 10;
43+
mul *= 10;
44+
}
45+
return result;
46+
}
47+
48+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.smlnskgmail.jaman.leetcodejava.easy;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertEquals;
6+
7+
public class LargestNumberAfterDigitSwapsByParityTest {
8+
9+
@Test
10+
public void defaultTest() {
11+
assertEquals(
12+
3412,
13+
new LargestNumberAfterDigitSwapsByParity(1234).solution()
14+
);
15+
}
16+
17+
}

0 commit comments

Comments
 (0)