1694. Reformat Phone Number

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 1694

class Solution:
    def reformatNumber(self, number: str) -> str:
        number = number.replace("-", "").replace(" ", "")
        n = len(number)
        res = [number[i * 3 : i * 3 + 3] for i in range(n // 3)]
        if n % 3 == 1:
            res[-1] = res[-1][:2]
            res.append(number[-2:])
        elif n % 3 == 2:
            res.append(number[-2:])
        return "-".join(res)