File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 202420242226|[ Maximum Candies Allocated to K Children] ( ./solutions/2226-maximum-candies-allocated-to-k-children.js ) |Medium|
202520252227|[ Encrypt and Decrypt Strings] ( ./solutions/2227-encrypt-and-decrypt-strings.js ) |Hard|
202620262229|[ Check if an Array Is Consecutive] ( ./solutions/2229-check-if-an-array-is-consecutive.js ) |Easy|
2027+ 2231|[ Largest Number After Digit Swaps by Parity] ( ./solutions/2231-largest-number-after-digit-swaps-by-parity.js ) |Easy|
202720282232|[ Minimize Result by Adding Parentheses to Expression] ( ./solutions/2232-minimize-result-by-adding-parentheses-to-expression.js ) |Medium|
202820292234|[ Maximum Total Beauty of the Gardens] ( ./solutions/2234-maximum-total-beauty-of-the-gardens.js ) |Hard|
202920302235|[ Add Two Integers] ( ./solutions/2235-add-two-integers.js ) |Easy|
Original file line number Diff line number Diff line change 1+ /**
2+ * 2231. Largest Number After Digit Swaps by Parity
3+ * https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/
4+ * Difficulty: Easy
5+ *
6+ * You are given a positive integer num. You may swap any two digits of num that have the
7+ * same parity (i.e. both odd digits or both even digits).
8+ *
9+ * Return the largest possible value of num after any number of swaps.
10+ */
11+
12+ /**
13+ * @param {number } num
14+ * @return {number }
15+ */
16+ var largestInteger = function ( num ) {
17+ const digits = num . toString ( ) . split ( '' ) . map ( Number ) ;
18+ const evenDigits = [ ] ;
19+ const oddDigits = [ ] ;
20+
21+ for ( const digit of digits ) {
22+ if ( digit % 2 === 0 ) {
23+ evenDigits . push ( digit ) ;
24+ } else {
25+ oddDigits . push ( digit ) ;
26+ }
27+ }
28+
29+ evenDigits . sort ( ( a , b ) => b - a ) ;
30+ oddDigits . sort ( ( a , b ) => b - a ) ;
31+
32+ let evenIndex = 0 ;
33+ let oddIndex = 0 ;
34+ const result = [ ] ;
35+
36+ for ( const digit of digits ) {
37+ if ( digit % 2 === 0 ) {
38+ result . push ( evenDigits [ evenIndex ++ ] ) ;
39+ } else {
40+ result . push ( oddDigits [ oddIndex ++ ] ) ;
41+ }
42+ }
43+
44+ return parseInt ( result . join ( '' ) , 10 ) ;
45+ } ;
You can’t perform that action at this time.
0 commit comments