|
| 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