PAT甲级 1060 Are They Equal

原题链接:

https://pintia.cn/problem-sets/994805342720868352/exam/problems/type/7?problemSetProblemId=994805413520719872&page=0

注意点:

  1. 找出指数中,部分指数可能不只有1位。

代码:

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

#define endl '\n'

int N;
string A, B;

int findDot(string str) {//返回小数点的位置,当str中不含小数点时,返回str.size()
	for (int i = 0;i<str.size();i++) {
		if (str[i] == '.') {
			return i;
		}
	}
	return str.size();
}

string findSignificant(string str, int dotPos) {
	string ans;
	bool isStart=false;
	int startPos = -1;
	//大于1的从第一个非零数开始
	//小于1的从小数点后第一个非零数开始
	//从第一个非零数开始
	for (int i = 0; i < str.size(); i++) {
		if (ans.size() == N) {
			break;
		}
		//判断是否需要开始加入significant
		if (!isStart) {
			if (str[i] != '0'&&str[i]!='.') {
				isStart = true;
				startPos = i;
			}
		}
		if (isStart && i != dotPos) {
			ans.push_back(str[i]);
		}
	}
	while (ans.size() < N) {
		ans.push_back('0');
		if (startPos == -1) {
			startPos = dotPos + 1;
		}
	}
	return ans;
}

string int2String(int x) {
	string ans;
	stack<int> s;
	while (x != 0) {
		s.push(x % 10);
		x /= 10;
	}
	while (s.size()) {
		ans += s.top() + '0';
		s.pop();
	}
	return ans;
}

string findExp(string str,int dotPos) {//x代表任何数,y代表大于0的数
	string ans;
	int state = -1;//-1代表未确定str种类,0代表0.0xxxx,1代表0.yyyy,2代表xxxxy.xxxx;
	for (int i = 0; i <dotPos; i++) {
		if (str[i] != '0') {//小数点前有大于0的数
			ans = int2String(dotPos - i);
			return ans;
		}
	}
	for (int i = dotPos + 1; i < str.size(); i++) {
		if (str[i] != '0') {//小数点后有大于0的数
			if (i == dotPos + 1) {
				return "0";
			}
			else {
				ans += '-';
				ans += int2String(i - dotPos-1);
				return ans;
			}
		}
	}
	//str值为0
	return "0";
}

string parseStandard(string str) {
	int dotPos = findDot(str);
	string ans = "0.";
	ans += findSignificant(str, dotPos);
	ans += "*10^";
	ans += findExp(str,dotPos);
	//cout << ans << endl;
	return ans;

}

signed main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

	cin >> N >> A >> B;
	string ansA, ansB;
	ansA=parseStandard(A);
	ansB=parseStandard(B);

	if (ansA == ansB) {
		cout << "YES " << ansA << endl;
	}
	else {
		cout << "NO " << ansA << " " << ansB << endl;
	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值