【PAT甲级】1060 Are They Equal (25分)

解题过程的小记录,如有错误欢迎指出。

难度:三星(简单题但需要考虑的方面很多,特别是数字前有0真的没想到orz)

题目分析

给出两个数,看它们在保留某一相同位数的科学进制法下是否完全一致

注意点

  1. 需要考虑前面含有0的数字,如00123,000.123之类
  2. 不考虑四舍五入

我的解题过程

思路

  1. 将输入的两个数用string保存
  2. 写一个chopping函数返回转化为要求输出的字符串
  3. 在chopping函数中,先去除开头多余的0(如00123),再按是否开头为‘0’以及是否含有小数点分类讨论
  4. 将两个数用chopping返回的字符串进行比较,看是否一致

bug

这题因为要考虑的方面很多,所以边测试边写,特别要注意0的输出问题(如0,0.00)
不过真的没想到如00123和00.000的数字写法,所以报错了两个测试点

代码

#include<iostream>
#include<string>

using namespace std;

int n;

string chopping(string num) {
	string result = "0.";
	while (num[0] == '0'&&num[1] != '.'&&num.size() > 2) {
		num = num.substr(1);
	}
	if (num[0] == '0') {
		if (num.find(".") == string::npos) {
			int t = n;
			while (t != 0) {
				result += "0";
				t--;
			}
			result += "*10^0";
			return result;
		}
		else {
			int pos = 2;
			while (num[pos] == '0'&&pos < num.size()) pos++;
			if (pos == num.size()) {
				int t = n;
				while (t != 0) {
					result += "0";
					t--;
				}
				result += "*10^0";
			}
			else {
				if(num.substr(pos).size()>=n)
					result += num.substr(pos, n);
				else {
					result += num.substr(pos);
					int t = n - num.substr(pos).size();
					while (t-- != 0) result += "0";
				}
				result += "*10^";
				if (pos > 2) result += "-";
				result += to_string(pos - 2);
			}
		}
	}
	else {
		if (num.find(".") == string::npos) {
			if (num.size() >= n) result += num.substr(0, n);
			else {
				result += num;
				int t = n - num.size();
				while (t-- != 0) {
					result += "0";
				}
			}
			result += "*10^";
			result += to_string(num.size());
		}
		else {
			int pos = num.find(".");
			num.erase(num.begin() + pos);
			if(num.size()>=n) result += num.substr(0, n);
			else {
				result += num;
				int t = n - num.size();
				while (t-- != 0) {
					result += "0";
				}
			}
			result += "*10^";
			result += to_string(pos);
		}
	}
	return result;
}

int main()
{	
	string a, b;
	//n = 4;//测试用
	//cout << chopping("00.000") << endl;//测试用
	cin >> n >> a >> b;
	if (chopping(a) == chopping(b)) cout << "YES " << chopping(a);
	else cout << "NO " << chopping(a) << " " << chopping(b);
    return 0;
}

dalao的代码

全部代码因版权原因不放出来,大家可以自行去柳神博客购买或者参考晴神的上机笔记~

借鉴点

  1. 去掉前导0的时候可以把在小数点前的所有0都去掉,这样如果num[0]是小数点的话说明是小于1的数
  2. 本题每个人的思考方式不一样,在考虑全面的情况下,用自己习惯的就好,适应别人的太累,为了考虑全面最好背一下科学计数法容易出错的几个点(000.0000,123.478,0.00123,00123.147),然后边做边进行测试
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值