小M在工作时遇到了一个问题,他需要将用户输入的不带千分位逗号的数字字符串转换为带千分位逗号的格式,并且保留小数部分。小M还发现,有时候输入的数字字符串前面会有无用的 0,这些也需要精简掉。请你帮助小M编写程序,完成这个任务。
#include
#include
std::string solution(const std::string& s) { // 去除前导零 size_t start = s.find_first_not_of('0'); if (start == std::string::npos) { start = s.size() - 1; // 如果全是零,保留一个零 } std::string trimmed = s.substr(start);
// 分离整数部分和小数部分
size_t dotPos = trimmed.find('.');
std::string integerPart, fractionalPart;
if (dotPos != std::string::npos) {
integerPart = trimmed.substr(0, dotPos);
fractionalPart = trimmed.substr(dotPos);
} else {
integerPart = trimmed;
}
// 处理整数部分,从后往前每三位插入一个逗号
std::string result;
int count = 0;
for (int i = integerPart.size() - 1; i >= 0; --i) {
result.insert(result.begin(), integerPart[i]);
count++;
if (count % 3 == 0 && i != 0) {
result.insert(result.begin(), ',');
}
}
// 合并整数部分和小数部分
if (!fractionalPart.empty()) {
result += fractionalPart;
}
return result;
}
int main() {
std::cout << (solution("1294512.12412") == "1,294,512.12412") << std::endl;
std::cout << (solution("0000123456789.99") == "123,456,789.99") << std::endl;
std::cout << (solution("987654321") == "987,654,321") << std::endl;
}