牛客刷题-Day22
牛客刷题-Day22
今日刷题:\(1036-1040\)
1036 习题-四舍五入

解题思路
- 不存在小数点,直接输出;
- 从小数点后第一位往后寻找第一个大于等于 \(5\) 的位置,后面即使再怎么可以进位都不会比从该位置进位的数大。当前面连续若干位为 \(4\),则可以继续进位。
C++ 代码
#include <bits/stdc++.h>
using namespace std;
string s;
int n, t;
int len; // 四舍五入后字符串的长度
int main() {
cin >> n >> t >> s;
int pos = s.find('.');
if (pos == -1) {
cout << s;
return 0;
}
len = n;
for (int i = pos + 1; i < n; i++) {
if(s[i] >= '5') {
len = i;
t--, i--;
while (s[i] == '4' && t != 0) { // 当前位为 4 可以继续往前
len = i;
t--, i--;
}
if (s[i] == '.') { // 到达小数点
len = i, i--;
while (s[i] == '9') {
s[i] = '0';
i--;
}
if (i == -1) // 进位到最前面
cout << '1';
else s[i] += 1;
}
else
s[i] += 1;
break;
}
}
for(int i = 0; i < len; i ++)
cout << s[i];
return 0;
}
1037 习题-安卓图案解锁

解题思路
对于中间存在数字的数字进行染色,\(\{1,3,7,9\}\) 一组,\(\{2,8\}\) 一组,\(\{4,6\}\) 一组。
特殊情况:字符串长度超过 \(9\),必然会存在重复。
判断是否该数字是否已用过,未用过,判断字符串中相邻两个数字是否为同组。
C++ 代码
#include <bits/stdc++.h>
using namespace std;
string s;
int color[] = {0, 1, 2, 1, 3, 0, 3, 1, 2, 1};
bool solve() {
set<int> tmp;
if (s.size() > 9)
return false;
for (int i = 0; s[i]; i++) {
if (tmp.find(s[i] - '0') != tmp.end())
return false;
if (tmp.size()) {
int a = s[i] - '0', b = s[i - 1] - '0';
if (color[a] == color[b] && tmp.find(a + b >> 1) == tmp.end())
return false;
}
tmp.insert(s[i] - '0');
}
return true;
}
int main() {
while (cin >> s) {
if (solve())
puts("YES");
else
puts("NO");
}
return 0;
}
1038 习题-从后台研发到跑路

解题思路
用两个栈分别存储注释符号和引号。
若注释栈不为空,则判断当前字符和下一个字符是否可以构成封闭注释,可以则弹出注释栈,否则当前字符不输出。
若注释栈为空:
- 引号栈为空,则判断当前字符和下一个字符是否可以构成注释,可以则入栈,否则直接输出当前字符;
- 判断当前字符和下一个字符是否可以转义引号,可以则直接输出这两个字符;
- 当前字符为引号,且引号栈不空,则弹出,否则插入引号,当前字符输出。
最后判断注释栈是否清空,若不空则存在不闭合的注释,则需要从注释符号的位置到最后输出所有的字符。
C++ 代码
#include <bits/stdc++.h>
using namespace std;
string str, last;
stack<int> note;
stack<int> quote;
int main() {
while (getline(cin, str)) {
str += '\n';
last = str;
for (int i = 0; str[i]; i++) {
if (!note.empty()) { // 注释
if (str[i] == '*' && i + 1 < str.size() && str[i + 1] == '/') {
note.pop();
i++;
} else {
continue;
}
} else {
if (str[i] == '/' && i + 1 < str.size() && str[i + 1] == '*') {
if (quote.empty()) { // 不在引号内部
note.push(i);
i++;
} else {
cout << str[i];
}
} else if (str[i] == '\\' && i + 1 < str.size() && str[i + 1] == '"') {
// cout << "flag" << endl;
cout << str[i] << str[i + 1]; // 转义直接输出
i++;
} else {
if (str[i] == '"') { // 引号
if (!quote.empty())
quote.pop();
else
quote.push(i);
}
cout << str[i];
}
}
}
}
if (!note.empty()) {
int k = note.top();
for (int i = k; last[i]; i++)
cout << last[i];
}
return 0;
}
本文来自博客园,作者:Cocoicobird,转载请注明原文链接:https://www.cnblogs.com/Cocoicobird/p/19211857
浙公网安备 33010602011771号