Skip to content

1556. Thousand Separator 👍

  • Time: $O(\log n)$
  • Space: $O(\log n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  string thousandSeparator(int n) {
    const string s = to_string(n);
    string ans;

    for (int i = 0; i < s.length(); ++i) {
      if (i > 0 && (s.length() - i) % 3 == 0)
        ans += '.';
      ans += s[i];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public String thousandSeparator(int n) {
    final String s = Integer.toString(n);
    StringBuilder ans = new StringBuilder();

    for (int i = 0; i < s.length(); ++i) {
      if (i > 0 && (s.length() - i) % 3 == 0)
        ans.append('.');
      ans.append(s.charAt(i));
    }

    return ans.toString();
  }
}
1
2
3
class Solution:
  def thousandSeparator(self, n: int) -> str:
    return f'{n:,}'.replace(',', '.')