Leetcode Problem 1694. Reformat Phone Number

1694. Reformat Phone Number

Leetcode Solutions

Iterative Grouping and Reformatting

  1. Initialize an empty string cleaned to store digits only.
  2. Iterate through each character in the input number and append only digit characters to cleaned.
  3. Initialize an empty string formatted to store the final phone number.
  4. Use a while loop to process the cleaned string:
    • If the length of cleaned is greater than 4, take the first 3 digits, append them to formatted, and remove them from cleaned.
    • If the length of cleaned is exactly 4, split it into two blocks of 2 digits, append them to formatted, and break the loop.
    • If the length of cleaned is less than 4, append the remaining digits to formatted and break the loop.
  5. Return the formatted string.
UML Thumbnail

Regex and Conditional Formatting

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...