Skip to content

Commit b89f7fb

Browse files
authored
Create Smallest Value of the Rearranged Number.java
1 parent 7f56b04 commit b89f7fb

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public long smallestNumber(long num) {
3+
return num < 0 ?
4+
getArrangement(Math.abs(num), (o1, o2) -> (int) (o2 - o1), true) * -1 :
5+
getArrangement(num, (o1, o2) -> (int) (o1 - o2), false);
6+
}
7+
8+
private long getArrangement(long num, Comparator<Long> comparator, boolean zeroAtEnd) {
9+
PriorityQueue<Long> pq = new PriorityQueue<>(comparator);
10+
long zeroMultiple = 1;
11+
while (num > 0) {
12+
long remainder = num % 10;
13+
if (remainder == 0) {
14+
zeroMultiple *= 10;
15+
} else {
16+
pq.add(remainder);
17+
}
18+
num /= 10;
19+
}
20+
long result = 0;
21+
if (!pq.isEmpty()) {
22+
result = result * 10 + pq.poll();
23+
}
24+
if (!zeroAtEnd) {
25+
result *= zeroMultiple;
26+
}
27+
while (!pq.isEmpty()) {
28+
result = result * 10 + pq.poll();
29+
}
30+
if (zeroAtEnd) {
31+
result *= zeroMultiple;
32+
}
33+
return result;
34+
}
35+
}

0 commit comments

Comments
 (0)