用double保存数字,在输出的时候加0.5取整。
doube n;
cout<<int(n+0.5);
字符串缩写
题目描述
对字符串进行缩写,如果有连续的M个(M>=4)按字典递增顺序相邻的大写字母,则缩写为“首个字母-结束字母”的形式
如:XYZABCDMMMGHIJKLRST缩写为XYZA-DMMMG-LRST
输入:
3
DCBA
ZABCDEFGX
XYZABCDMMMGHIJKLRST
输出:
DCBA
ZA-GX
XYZA-DMMMG-LRST
#include<iostream>
#include<vector>
#include<string>
using namespace std;
string convert(string& s) {
string str;
str += s[0];
str += '-';
str += s.back();
return str;
}
int main() {
int n;
cin >> n;
string s;
vector<string> test;
for (int i = 0; i<n; i++) {
cin >> s;
test.push_back(s);
}
for (int i = 0; i<n; i++) {
s = test[i];
s += '1';
string result;
int len = s.size();
int times = 0;
int p = 0;
int j = 0;
for (; j<len; j++) {
if (s[j] + 1 == s[j+1]) {
times++;
}
else {
if (times >= 3) {
string r = string(s.begin() + p, s.begin() + j + 1);
result += convert(r);
times = 0;
p = j+1;
continue;
}
else {
string r = string(s.begin() + p, s.begin() + j + 1);
result += r;
p = j + 1;
times = 0;
}
}
}
result.pop_back();
cout << result << endl;
}
}
进制转换