20.8.23 周赛 5479. 千位分隔数 简单

题目

给你一个整数 n,请你每隔三位添加点(即 "." 符号)作为千位分隔符,并将结果以字符串格式返回。

示例 1:

输入:n = 987
输出:"987"
示例 2:

输入:n = 1234
输出:"1.234"
示例 3:

输入:n = 123456789
输出:"123.456.789"
示例 4:

输入:n = 0
输出:"0"

提示:

0 <= n < 2^31

思路

  1. 先将这个整数变成字符串
  2. 从右到左遍历字符串,每三个加一个点
  3. 最后输出结果

代码

//这是脑瘫写法
class Solution {
public:
    string thousandSeparator(int n) {
        if(n == 0) return "0";
        string res;
        string str;
        while(n/1000){
            int save = n%1000;
            int i = 3;
            while(i--){
                str = to_string(save%10);
                res.append(str);
                save /= 10;
            }
            res.push_back('.');
            n /= 1000;
        }
        while(n){
            str = to_string(n%10);
            res.append(str);
            n /= 10;
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

//看题解后
class Solution {
public:
    string thousandSeparator(int n) {
        string save = to_string(n);
        
        int count = 0;
        string res;
        for(int i = save.size()-1; i >= 0; i--){
            res.push_back(save[i]);
            count++;
            if(count % 3 == 0 && i != 0){
                res.push_back('.');
            }
        }
        
        reverse(res.begin(), res.end());
        return res;
    }
};

posted @ 2020-08-23 00:28  肥斯大只仔  阅读(137)  评论(0编辑  收藏  举报