PAT A1060 -《算法笔记》

前言:

21考研,正在啃《算法笔记》,不论能否进复试记录一下准备路上写下的垃圾代码。

解答:

#include<iostream>
#include<string>
using namespace std;

string deal(string str, int &e,int n) {
    
    
	if (str.find(".") == -1) {
    
    						//对于无小数点整数添上一个
		str += ".";
	}
	while (str[0] == '0')							//去除前面多于的0
		str.erase(0, 1);
	while (str[str.length() - 1] == '0')			//去除后面多余的0
		str.erase(str.length() - 1, 1);
	if (str[0] == '.') {
    
    							//整数部分为0情形
		if (str.length() != 1) {
    
    					//小数部分有非0数字情形
			while (str[1] == '0') {
    
    
				str.erase(1, 1);
				e--;
			}
			if (str.length() > n + 1) {
    
    
				str.erase(n + 1, str.length());
			}
		}
		else {
    
    										//防止对于000.000类似数据会出现的BUG,加上正确数量0
			while (str.length() - 1 != n)
				str.insert(1, "0");
		}
	}
	else {
    
    											//整数部分不为0情形
		e = str.find(".");
		str.erase(str.find("."), 1);				//去掉小数点,最后统一添回
		while (str.length() < n)
			str += "0";
		while (str.length() > n)
			str.erase(str.length()-1, 1);
		str.insert(0, ".");
	}
	return str;
}
int main()
{
    
    
	string str1, str2,exp1,exp2;
	int n, e1=0, e2=0;
	cin >> n >> str1 >> str2;
	str1 = deal(str1, e1, n) ;
	str2 = deal(str2, e2, n) ;
	exp1 = to_string(e1);
	exp2 = to_string(e2);
	str1 = "0" + str1 + "*10^" + exp1;
	str2 = "0" + str2 + "*10^" + exp2;
	if (str1 == str2)
		cout << "YES" << ' ' << str1 << endl;
	else
		cout << "NO" << ' ' << str1 << ' ' << str2 << endl;
 	return 0;
}

情形有点多,写的头疼,这个输入也是各种坑,各种奇奇怪怪的数字输入。

猜你喜欢

转载自blog.csdn.net/weixin_44897291/article/details/112750804
今日推荐