Skip to content

Commit 7e51cfe

Browse files
committed
Add solution #1694
1 parent fb91d65 commit 7e51cfe

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,479 LeetCode solutions in JavaScript
1+
# 1,480 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1304,6 +1304,7 @@
13041304
1689|[Partitioning Into Minimum Number Of Deci-Binary Numbers](./solutions/1689-partitioning-into-minimum-number-of-deci-binary-numbers.js)|Medium|
13051305
1690|[Stone Game VII](./solutions/1690-stone-game-vii.js)|Medium|
13061306
1691|[Maximum Height by Stacking Cuboids](./solutions/1691-maximum-height-by-stacking-cuboids.js)|Hard|
1307+
1694|[Reformat Phone Number](./solutions/1694-reformat-phone-number.js)|Easy|
13071308
1716|[Calculate Money in Leetcode Bank](./solutions/1716-calculate-money-in-leetcode-bank.js)|Easy|
13081309
1718|[Construct the Lexicographically Largest Valid Sequence](./solutions/1718-construct-the-lexicographically-largest-valid-sequence.js)|Medium|
13091310
1726|[Tuple with Same Product](./solutions/1726-tuple-with-same-product.js)|Medium|
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 1694. Reformat Phone Number
3+
* https://leetcode.com/problems/reformat-phone-number/
4+
* Difficulty: Easy
5+
*
6+
* You are given a phone number as a string number. number consists of digits, spaces ' ',
7+
* and/or dashes '-'.
8+
*
9+
* You would like to reformat the phone number in a certain manner. Firstly, remove all spaces
10+
* and dashes. Then, group the digits from left to right into blocks of length 3 until there
11+
* are 4 or fewer digits. The final digits are then grouped as follows:
12+
* - 2 digits: A single block of length 2.
13+
* - 3 digits: A single block of length 3.
14+
* - 4 digits: Two blocks of length 2 each.
15+
*
16+
* The blocks are then joined by dashes. Notice that the reformatting process should never produce
17+
* any blocks of length 1 and produce at most two blocks of length 2.
18+
*
19+
* Return the phone number after formatting.
20+
*/
21+
22+
/**
23+
* @param {string} number
24+
* @return {string}
25+
*/
26+
var reformatNumber = function(number) {
27+
const digits = number.replace(/[^0-9]/g, '');
28+
const blocks = [];
29+
let i = 0;
30+
31+
while (i < digits.length) {
32+
const remaining = digits.length - i;
33+
if (remaining > 4) {
34+
blocks.push(digits.slice(i, i + 3));
35+
i += 3;
36+
} else if (remaining === 4) {
37+
blocks.push(digits.slice(i, i + 2), digits.slice(i + 2));
38+
break;
39+
} else if (remaining === 2 || remaining === 3) {
40+
blocks.push(digits.slice(i));
41+
break;
42+
}
43+
}
44+
45+
return blocks.join('-');
46+
};

0 commit comments

Comments
 (0)