0
点赞
收藏
分享

微信扫一扫

【PTA做题笔记】L1-3 强迫症 (10 分)

小时候是个乖乖 2022-03-30 阅读 79
c++

问题1:如何解决区分输入的数据是六位数还是两位数呢?

最先想到的是通过除10,再count++来判断数据为几位数,但是该方法明显时间复杂度太大,不方便!

解决:

后面经过一番思考,数据除以1w是最好的解决办法,四位数除以一万小于1,C++默认整形,最终结果为零。

五位/六位数据输出则保留万位和十万位。

问题2:如何获取数据的最后末尾两个数字呢?

解决:采用模100的方式得到。

cout<<196710%100; 

这样就得到了10。

问题3:如何获取前四位/两位数据呢?

解决:采用Data/100即可。

cout<<196710/100; 

代码如下:

#include<iostream>	
using namespace std;
int main()
{
	long int Data;
	int month;
	int year;
	cin >> Data;//输入数据
	
	if ((Data / 10000) != 0)//判断为六位数据
	{
		month = Data % 100;
		year = Data / 100;
		if(month<10)
		cout << year << "-" <<"0" << month;
		else
		cout << year << "-" << month;
	}
	else//否则为四位数据
	{
		month = Data % 100;
		year = Data / 100;
		if (year < 22&&month<10)
			cout << "20" << year << "-"<<"0" << month;
		 if(year>=22&&month<10)
			cout << "19" << year << "-" << "0" << month;
		 if (year < 22 )
			 cout << "20" << year << "-"  << month;
		 if (year >= 22 )
			 cout << "19" << year << "-" << month;
	}

	return 0;
}

再下面是别人的解法

利用string数组存储各个数字,非常精妙。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
    string str;
    getline(cin,str);
    if(str.size()==4)
    {
        if((str[0]-'0')*10+(str[1]-'0')<22)
        {
            printf("20%c%c-%c%c\n",str[0],str[1],str[2],str[3]);
        }
        else
        {
            printf("19%c%c-%c%c\n",str[0],str[1],str[2],str[3]);
        }
    }
    else
    {
        printf("%c%c%c%c-%c%c\n",str[0],str[1],str[2],str[3],str[4],str[5]);
    }
    
    return 0;
}
举报

相关推荐

0 条评论