第3章入门篇(1)–入门模拟(2)
3.4 日期处理
codeup 1928 日期差值
#include <iostream>
using namespace std;
int month[13][2]={
{0,0},{31,31},{28,29},{31,31},{30,30},{31,31},{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}
};
bool isLeap(int year){
return (year%4==0&&year%100!=0)||(year%400==0);
}
int main(){
int time1,y1,m1,d1;
int time2,y2,m2,d2;
while(scanf("%d%d",&time1,&time2)!=EOF){
if(time1>time2){
int temp=time1;
time1=time2;
time2=temp;
}
y1=time1/10000,m1=time1%10000/100,d1=time1%100;
y2=time2/10000,m2=time2%10000/100,d2=time2%100;
int ans=1;
while(y1<y2||m1<m2||d1<d2){
d1++;
if(d1==month[m1][isLeap(y1)]+1){
m1++;
d1=1;
}
if(m1==13){
y1++;
m1=1;
}
ans++;
}
printf("%d\n",ans);
}
return 0;
}
注:求日期之间相差天数的题目有一个直接的思路:令日期不断加1天,直到第一个日期等于第二个日期为止。具体处理时,如果当加了一天之后天数d等于当前月份m所拥有的天数加1,那么就令月份m加1.同时置天数d为1号(下个月1号);如果此时月份变为13,那么就令年份y加1、同时置月份m为1月。
3.5 进制转换
对于一个P进制的数,如果要转换为Q进制,需要分为两步:
- 将P进制数x转换为十进制数y
int y=0,product=1;
while(x!=0){
y=y+(x%10)*product;
x=x/10;
product=product*p;
}
- 将十进制数y转换为Q进制数z(采用“除基取余”法)
int z[40],num=0;
do{
z[num++]=y%Q;
y=y/Q;
}while(y!=0);
PAT B1022
#include <iostream>
using namespace std;
int main(){
int a,b,d;
scanf("%d%d%d",&a,&b,&d);
int sum=a+b;
int ans[31],num=0;
do{
ans[num++]=sum%d;
sum/=d;
}while(sum!=0);
for(int i=num-1;i>=0;i--){
printf("%d",ans[i]);
}
return 0;
}
3.6 字符串处理
这类题目要仔细分析清楚题目中的输入和输出格式。
codeup 5901 回文串
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=256;
bool judge(char str[]){
int len=strlen(str);
for(int i=0;i<len/2;i++){
if(str[i]!=str[len-1-i]){
return false;
}
}
return true;
}
int main(){
char str[maxn];
while(gets(str)){
bool flag=judge(str);
if(flag==true){
printf("YES\n");
}else{
printf("NO\n");
}
}
return 0;
}
PAT B1009
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<string> v;
string s;
while(cin >> s) v.push(s);
cout << v.top();
v.pop();
while(!v.empty()) {
cout << " " << v.top();
v.pop();
}
return 0;
}