LeetCode solutions

1812. Reformat Phone Number

My accepted Python solution to LeetCode problem 1812, Reformat Phone Number, running in 0ms.

  • Difficulty: Easy
  • Python
  • Runtime 0ms
  • Memory 17MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 0ms, memory 17MB, accepted 2025-12-30.

python
class Solution:
    def reformatNumber(self, number: str) -> str:
        digits = ''.join(c for c in number if c.isdigit())
        result = []
        i = 0
        while len(digits) - i > 4:
            result.append(digits[i:i+3])
            i += 3
        if len(digits) - i == 4:
            result.append(digits[i:i+2])
            result.append(digits[i+2:i+4])
        else:
            result.append(digits[i:])
        return '-'.join(result)

Source