-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargNumAftSwap.java
More file actions
70 lines (59 loc) · 2.33 KB
/
LargNumAftSwap.java
File metadata and controls
70 lines (59 loc) · 2.33 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.*;
public class LargNumAftSwap {
public int largestInteger(String num) {
// Separate digits by parity
ArrayList<Character> oddDigits = new ArrayList<>();
ArrayList<Character> evenDigits = new ArrayList<>();
for (char digit : num.toCharArray()) {
if ((digit - '0') % 2 == 0) {
evenDigits.add(digit);
System.out.println("evenDigits: " + evenDigits);
} else {
oddDigits.add(digit);
System.out.println("oddDigits: " + oddDigits);
}
}
// Sort the digits in descending order
Collections.sort(oddDigits, Collections.reverseOrder());
System.out.println("oddDigits sorted: " + oddDigits);
Collections.sort(evenDigits, Collections.reverseOrder());
System.out.println("evenDigits sorted: " + evenDigits);
// Initialize the result
StringBuilder result = new StringBuilder();
// Pointers for odd and even digits
int oddIndex = 0;
int evenIndex = 0;
// Construct the result by replacing digits with sorted ones
for (char digit : num.toCharArray()) {
if ((digit - '0') % 2 == 0) {
result.append(evenDigits.get(evenIndex));
System.out.println("result36: " + result);
evenIndex++;
} else {
result.append(oddDigits.get(oddIndex));
System.out.println("result40: " + result);
oddIndex++;
}
}
// Convert the result string to an integer using Integer.valueOf
return Integer.valueOf(result.toString());
}
public static void main(String[] args) {
LargNumAftSwap solution = new LargNumAftSwap();
// Example 1
String number1 = "1234";
int largestNumber1 = solution.largestInteger(number1);
System.out.println(largestNumber1); // Output: 3412
// Example 2
String number2 = "65875";
int largestNumber2 = solution.largestInteger(number2);
System.out.println(largestNumber2); // Output: 87655
}
}
/*
* https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/description/
* However, this code inputs num as a string
* Did not pass HackerRank though; error on converting to int
*
*
* */