PAT Advanced 1060 Are They Equal (25 )

题目描述

在这里插入图片描述

Input Specification:

在这里插入图片描述

Output Specification:

在这里插入图片描述

Sample Input:

在这里插入图片描述

Sample Output:

在这里插入图片描述

解题思路

超烦的一类题,消极写题然后WA到没脾气,一个地方一个地方的找bug。。
比如前缀0。。。以及00000000.0001这样的数据。。

Code

  • AC代码
#include<bits/stdc++.h>
using namespace std;
string getZeros(int num) {
	if(!num) return "";
	return "0"+getZeros(num-1); 
}
string dealPrefix0(string str) {
	int i = 0;
	while(i<str.length() && str[i] == '0') i++;
	if(i == str.length()) return "0";
	else if(str[i] == '.') return str.substr(i-1);
	return str.substr(i);
}
string getStandardFormat(string str, int digits, int &e) {
	str = dealPrefix0(str);
	int dotIdx = str.find('.');
	if(dotIdx == -1) {
		//整数 	
		if(str == "0") return getZeros(digits);
		e = str.length();
		return e >= digits ? str.substr(0, digits) : str+getZeros(digits-e);
	} else if(dotIdx == 1 && str[0] == '0') {
		//纯小数
		int nonZeroIdx = 2;
		while(nonZeroIdx < str.length() && str[nonZeroIdx] == '0') nonZeroIdx++;
		int validCount = str.length()-1;
		while(validCount>nonZeroIdx && str[validCount] == '0') validCount--;
		validCount = validCount - nonZeroIdx + 1;
		if(validCount > 0) {
			e = 2-nonZeroIdx;
			return validCount >= digits ? str.substr(nonZeroIdx, digits) : str.substr(nonZeroIdx)+getZeros(digits-validCount);
		} else {
			//0.0...0
			return getZeros(digits);
		} 
	} else {
		//整数+小数
		e = dotIdx;
		if(e >= digits) {
			return str.substr(0, digits);
		} else {
			string res = str.substr(0, dotIdx)+str.substr(dotIdx+1, str.length()-dotIdx);
			return res.length() > digits ? res.substr(0, digits) : res+getZeros(digits-res.length());
		}
	}
}
void printFormat(string str, int e) {
	cout << " 0." << str;
	cout << "*10^" << e;
}
int main() {
	freopen("in.txt", "r", stdin);
	int digits, e1 = 0, e2 = 0;
	string num1, num2;
	cin >> digits >> num1 >> num2;
	string format1 = getStandardFormat(num1, digits, e1);
	string format2 = getStandardFormat(num2, digits, e2);
	if(format1 == format2 && e1 == e2) {
		cout << "YES";
		printFormat(format1, e1);
	} else {
		cout << "NO";
		printFormat(format1, e1);
		printFormat(format2, e2);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值