PAT 1069 题解
#include<iostream>
#include<algorithm>
using namespace std;
int NUM = 6174;
int x = 0, y = 0;
int a[4];
void aa(int num){
x = 0, y = 0;
for (int i = 0; i < 4; i++){
a[i] = num % 10;
num /= 10;
}
sort(a, a+4, greater<int>());
for (int i = 0; i < 4; i++){
x = x * 10 + a[i];
}
sort(a, a+4, less<int>());
for (int i = 0; i < 4; i++){
y = y * 10 + a[i];
}
}
int main(){
int num;
cin >> num;
aa(num);
int c = x - y;
if (x == y)
printf("%04d - %04d = %04d\n", x, y, c);
else{
printf("%04d - %04d = %04d\n", x, y, c);
while (c != 6174){
aa(c);
c = x - y;
printf("%04d - %04d = %04d\n", x, y, c);
}
}
return 0;
}
printf
格式化输出 printf格式化输出参数sort
函数的使用
升序:sort(begin, end, less<data-type>())
降序:sort(begin, end, greater<data-type>())
PAT 1059 题解
#include<iostream>
using namespace std;
const int maxn = 100010;
int prime[maxn] = {0};
int p[maxn]={0}, t = 0;
// 构造素数表
void findPrime(){
for (int i = 2; i < maxn; i++){
if (prime[i] == false){
p[t++] = i;
for (int j = i + i; j < maxn; j += i){
prime[j] = true;
}
}
}
}
int main(){
long int num;
cin >> num;
findPrime();
cout << num << "=";
long int cnt = 0;
while (num){
long int tmp = num % p[cnt];
if (tmp == 0)
{
cout << p[cnt];
int c = 0; // 幂指数
while (tmp == 0){
num = num / p[cnt];
tmp = num % p[cnt];
c++;
}
if (c != 1)
cout << "^" << c;
if (num != 1)
cout << "*";
}
cnt++;
}
return 0;
}
- 素数表的构建
奇怪的很,本地测试没有问题,上交平台测试报浮点错误。检查之后并未发现除以0或者取余0的情况。
PAT 1061 题解
#include<iostream>
using namespace std;
int main(){
string a, b, c, d;
cin >> a >> b >> c >> d;
string ss[7] = { "MON","TUE","WED","THU","FRI","SAT","SUN" };
int n = a.size() < b.size() ? a.size() : b.size();
int i = 0;
for (i = 0; i < n; i++){
if (a[i] == b[i]){
if (a[i] >= 'A' && a[i] <= 'G'){
cout << ss[a[i]-'A'] << " ";
break;
}
}
}
for (int k = i+1; k <= n; k++){
if (a[k] == b[k])
{
if (a[k] >= '0' && a[k] <= '9'){
cout << "0" << a[k] << ":";
break;
}
if (a[k] >= 'A' && a[k] <= 'N'){
cout << (a[k]-'A'+10) << ":";
break;
}
}
}
int n1 = c.size() < d.size() ? c.size() : d.size();
for (int i = 0; i < n1; i++){
if (c[i] == d[i]){
if (c[i] >= 'a' && c[i] <= 'z' || c[i] >= 'A' && c[i] <= 'Z'){
printf("%02d\n", i);
break;
}
}
}
return 0;
}
特别需要注意的是临界条件
- 星期:大写字母(A-G)
- 小时:0-9、A-N
- 分钟:英文字母(a-zA-Z)