carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1556:千位分隔数(thousand-separator) #245

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

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

 

示例 1:

输入:n = 987 输出:"987"

示例 2:

输入:n = 1234 输出:"1.234"

示例 3:

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

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

提示:

0 <= n < 2^31

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/thousand-separator

carloscn commented 1 year ago

问题分析

pub fn thousand_separator(n: i32) -> String
{
    let mut s_vec:Vec<char> = vec![];
    let mut dn:Vec<char> = i32::to_string(&n).chars().collect();
    let mut count:usize = 0;

    dn.reverse();

    for e in &dn {
        if count % 3 == 0 &&
           count != 0 &&
           count != dn.len() {
            s_vec.insert(0, '.');
        }
        s_vec.insert(0, *e);
        count += 1;
    }

    return s_vec.into_iter().collect::<String>();
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/555103 https://github.com/carloscn/structstudy/commit/0b6074c4ae8bd2adfbf98916269b96b42b0d5dc5