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

这题让我们格式化一个数字,在千位附近添加一个点。我这里遍历数字,每3次加一个点,然后反转一下即可。


class ThousandSeparator : public Solution {
public:
    void Exec() {

    }
    string thousandSeparator(int n) {
        if (n < 1000) {
            return std::to_string(n);
        }
        string res;
        int count = 0;
        while (n != 0) {
            if (count % 3 == 0 && count != 0) {
                res.push_back('.');
            }
            res.push_back(char('0' + (n % 10)));
            ++count;
            n /= 10;
        }
        std::reverse(res.begin(), res.end());
        return res;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day