Formatted question description: https://leetcode.ca/all/1556.html

1556. Thousand Separator (Easy)

Given an integer n, add a dot (".") as the thousands separator and return it in string format.

 

Example 1:

Input: n = 987
Output: "987"

Example 2:

Input: n = 1234
Output: "1.234"

Example 3:

Input: n = 123456789
Output: "123.456.789"

Example 4:

Input: n = 0
Output: "0"

 

Constraints:

  • 0 <= n < 2^31

Related Topics:
String

Solution 1.

// OJ: https://leetcode.com/problems/thousand-separator/

// Time: O(N)
// Space: O(1)
class Solution {
public:
    string thousandSeparator(int n) {
        if (n == 0) return "0";
        int d = 0;
        string ans;
        while (n) {
            ans += '0' + n % 10;
            n /= 10;
            if (++d % 3 == 0 && n) ans += '.';
        }
        reverse(begin(ans), end(ans));
        return ans;
    }
};

Java

class Solution {
    public String thousandSeparator(int n) {
        StringBuffer sb = new StringBuffer(String.valueOf(n));
        for (int i = sb.length() - 3; i > 0; i -= 3)
            sb.insert(i, '.');
        return sb.toString();
    }
}

All Problems

All Solutions