问题描述
小M在工作时遇到了一个问题,他需要将用户输入的不带千分位逗号的数字字符串转换为带千分位逗号的格式,并且保留小数部分。小M还发现,有时候输入的数字字符串前面会有无用的 0
,这些也需要精简掉。请你帮助小M编写程序,完成这个任务。
测试样例分析
样例1:
输入:s = "1294512.12412"//有小数点的话,小数点之后的字符不改变 输出:'1,294,512.12412'
样例2:
输入:s = "0000123456789.99"//字符前导零应该去掉 输出:'123,456,789.99'
样例3:
输入:s = "987654321"//正常类型 输出:'987,654,321'
思路: 1、去除前导零 遍历字符串,记录下第一个不为'\0'的字符的下标(jilu) 2、处理小数点前的有效字符 ①遍历字符串,遍历到小数点则记录小数点'.'的下标(dotIndex),否则记录字符串长度(dotIndex=len) ②(以样例二为例)将逆序下标dotIndex-1从到jilu的字符存储到队列中 获取队头元素(存储在char1中)并将队头元素pop出队列,每pop出三个字符则将','存入char1 ③将char1中的字符倒序存入char2中,此时char2中字符为整数部分格式化后的结果 3、整合所有字符 如果dotIndex小于字符串长度(len),说明有小数部分,将下标从dotIndex-1到len-1的字符存入char2,char2即为最终结果
算法小白写的该写法或许有点绕(但确实过了),上文众多描述也有不恰当之处,欢迎友友们指正交流。
图为队列演示
(添加逗号后字符总数一定不会大于2len,所以这里char1和char2的大小都设置为2len)
`#include
#include
#include
#include
using namespace std;
string solution(string s) { int len = s.length(); char char1[2 * len], char2[2 * len]; int jilu ,dotIndex=-1; // 找到第一个非零字符的位置 for(int i=0;i<len;i++){ if(s[i]!='0'){ jilu=i; break; } }
// 找到小数点的位置
for(int i=0;i<len;i++){
if(s[i]=='.'){
dotIndex =i;
break;
}
}
if(dotIndex ==-1){
dotIndex =len;
}
// 使用队列来处理整数部分的千分位
queue<char> st;
for (int i = dotIndex - 1; i >= jilu; i--) {
st.push(s[i]);
}
// 构建结果字符串
int mm = 0, kk = 0;
while (!st.empty()) {
if (mm > 0 && mm % 3 == 0) {
char1[kk++] = ',';
}
char1[kk++] = st.front();
st.pop();
mm++;
}
// 复制到 char2
for (int i = 0; i < kk; i++) {
char2[i] = char1[kk-1-i];
}
char2[kk] = '\0';
// 添加小数部分
if (dotIndex < len) {
for (int i = dotIndex; i < len; i++) {
char2[kk++] = s[i];
}
}
char2[kk] = '\0';
return char2;
}
int main() { std::cout << (solution("1294512.12412") == "1,294,512.12412") << std::endl; std::cout << (solution("0000123456789.99") == "0000123,456,789.99") << std::endl; std::cout << (solution("987654321") == "987,654,321") << std::endl; }`