Skip to content

Commit 23e5ba7

Browse files
committed
Add solution #2231
1 parent 16da511 commit 23e5ba7

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2024,6 +2024,7 @@
20242024
2226|[Maximum Candies Allocated to K Children](./solutions/2226-maximum-candies-allocated-to-k-children.js)|Medium|
20252025
2227|[Encrypt and Decrypt Strings](./solutions/2227-encrypt-and-decrypt-strings.js)|Hard|
20262026
2229|[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|
20272028
2232|[Minimize Result by Adding Parentheses to Expression](./solutions/2232-minimize-result-by-adding-parentheses-to-expression.js)|Medium|
20282029
2234|[Maximum Total Beauty of the Gardens](./solutions/2234-maximum-total-beauty-of-the-gardens.js)|Hard|
20292030
2235|[Add Two Integers](./solutions/2235-add-two-integers.js)|Easy|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy