1556. Thousand Separator

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
class Solution {
    public String thousandSeparator(int n) {
        String s = n + "";
        int le = s.length();
        StringBuilder res = new StringBuilder();
        if(le < 4) return s;
        int cur = 0;
        for(int i = le - 1; i > -1; i--) {
            if(cur % 3 == 0 && cur != 0) res.append(".");
            res.append(s.charAt(i));
            cur++;
        }
        return res.reverse().toString();
    }
}
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13584423.html