leetcode-1556-easy

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"
Constraints:

0 <= n <= 231 - 1

思路一:循环取余

public String thousandSeparator(int n) {
    if (n == 0) return "0";
    StringBuilder sb = new StringBuilder();

    int count = 0;
    while (n > 0) {
        if (count % 3 == 0 && count > 0) {
            sb.insert(0, '.');
        }

        sb.insert(0, n % 10);
        n /= 10;
        count++;
    }

    return sb.toString();
}
posted @ 2022-11-09 18:43  iyiluo  阅读(17)  评论(0)    收藏  举报