Skip to content

1694. Reformat Phone Number

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  string reformatNumber(string number) {
    string ans;

    std::erase(number, '-');
    std::erase(number, ' ');

    int i = 0;  // number's index
    for (i = 0; i + 4 < number.length(); i += 3)
      ans += number.substr(i, 3) + '-';

    const int countFinalDigits = number.length() - i;
    if (countFinalDigits < 4)
      ans += number.substr(i);
    else  // countFinalDigits == 4
      ans += number.substr(i, 2) + '-' + number.substr(i + 2);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public String reformatNumber(String number) {
    StringBuilder sb = new StringBuilder();

    number = number.replaceAll("[-\\s]", "");

    int i = 0; // number's index
    for (i = 0; i + 4 < number.length(); i += 3)
      sb.append(number.substring(i, i + 3) + '-');

    final int countFinalDigits = number.length() - i;
    if (countFinalDigits < 4)
      sb.append(number.substring(i));
    else // countFinalDigits == 4
      sb.append(number.substring(i, i + 2) + '-' + number.substring(i + 2));

    return sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def reformatNumber(self, number: str) -> str:
    ans = []

    number = number.replace("-", "").replace(" ", "")

    i = 0  # number's index
    while i + 4 < len(number):
      ans.append(number[i:i + 3] + '-')
      i += 3

    countFinalDigits = len(number) - i
    if countFinalDigits < 4:
      ans.append(number[i:])
    else:  # countFinalDigits == 4
      ans.append(number[i:i + 2] + '-' + number[i + 2:])

    return ''.join(ans)