这才是通俗易懂的题解
这才是不通俗易懂的题解
这个题解纯属娱乐了,先上代码:
#include <bits/stdc++.h>
using namespace std;
string content;
regex r1("[0-9]*%"); //100%
regex r2("[0-9]*"); //114514
regex r3(R"([0-9]*\.[0-9]*)"); //1.1
regex r4("[0-9]*/[0-9]*"); //1/1
long long str2llong(string str){
stringstream stream;
stream << str;
long long res;
stream >> res;
return res;
}
string removeLastZero(string numstr)
{
for (size_t i = numstr.size() - 1; i > 0; --i)
{
if ('\0' == numstr[i])
{
continue;
}
else if ('0' == numstr[i])
{
numstr[i] = '\0';
}
else if ('.' == numstr[i])
{
numstr[i] = '\0';
break;
}
else
{
break;
}
}
return numstr;
}
int main(int argc, char* argv[]){
cin >> content;
if(regex_search(content, r1)){
string ans = content.substr(0, content.length() - 1);
reverse(ans.begin(), ans.end());
cout << str2llong(ans) << "%";
}else if(regex_search(content, r3)){
bool flag = false;
string top = "";
string bottom = "";
for (size_t i = 0; i < content.size(); i++){
if (!flag){
if (content[i] == '.'){
flag=true;
}else{
top = top + content[i];
}
}else{
bottom = bottom + content[i];
}
}
reverse(top.begin(), top.end());
reverse(bottom.begin(), bottom.end());
bottom = removeLastZero(bottom);
cout << str2llong(top) << "." << str2llong(bottom);
}else if(regex_search(content, r4)){
bool flag = false;
string top = "";
string bottom = "";
for (size_t i = 0; i < content.size(); i++){
if (!flag){
if (content[i] == '/'){
flag=true;
}else{
top = top + content[i];
}
}else{
bottom = bottom + content[i];
}
}
reverse(top.begin(), top.end());
reverse(bottom.begin(), bottom.end());
cout << str2llong(top) << "/" << str2llong(bottom);
}else if(regex_search(content, r2)){
string ans = content;
reverse(ans.begin(), ans.end());
cout << str2llong(ans);
}
return 0;
}
其实没什么好讲的,我的思路是先用正则表达式匹配类型。由于表达式写的一些问题,有顺序要求:
1.匹配纯数字
2.匹配分数/小数
3…匹配分数/小数
4.匹配百分数
之后就是处理。
· 首先最简单的数字:
- 使用reverse颠倒字符串
- 输出
解决!
· 然后是稍微困难的百分数:
-
使用substr去除末尾的%
-
然后使用reverse颠倒字符串
-
输出
解决!
· 下一个是小数和分数
-
创建top和bottom变量
-
创建flag
-
遍历字符串
-
把"/“或”."之前的内容写入top
-
之后写入bottom
-
使用reverse颠倒字符串
-
输出
Tips: 为了去字符串前的0可以把字符串转换成longlong
· String To Longlong
-
创建stringstream
-
将str写入stringstream
-
创建long long
-
将stringstream输出到long long
-
返回long long
末尾去0麻烦一点,主要还是遍历