✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1060 Are They Equal (pintia.cn)
🔑中文翻译:它们是否相等
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
1060 Are They Equal
If a machine can save only 3 significant digits, the float numbers 12300 and 12358.9 are considered equal since they are both saved as 0.123×105 with simple chopping. Now given the number of significant digits on a machine and two float numbers, you are supposed to tell if they are treated equal in that machine.
Input Specification:
Each input file contains one test case which gives three numbers N, A and B, where N (<100) is the number of significant digits, and A and B are the two float numbers to be compared. Each float number is non-negative, no greater than 10100, and that its total digit number is less than 100.
Output Specification:
For each test case, print in a line
YES
if the two numbers are treated equal, and then the number in the standard form0.d[1]...d[N]*10^k
(d[1]
>0 unless the number is 0); orNO
if they are not treated equal, and then the two numbers in their standard form. All the terms must be separated by a space, with no extra space at the end of a line.Note: Simple chopping is assumed without rounding.
Sample Input 1:
3 12300 12358.9
Sample Output 1:
YES 0.123*10^5
Sample Input 2:
3 120 128
Sample Output 2:
NO 0.120*10^3 0.128*10^3
思路
这道题主要难点就在于将给定的浮点数转换成 0. x ∗ 1 0 y 0.x*10^y 0.x∗10y 的形式,我们这里来讲如何处理字符串:
- 先找到
.
,如果是整数需要人为在后面加上一个.
,因为我们要得到.
的位置 k k k ,用于分隔两边的数字。 - 将
.
两边的数字即字符串合并,然后去除多余的前缀 0 0 0 。 - 判断去除完 0 0 0 后字符串是否为空,要将 k k k 也置 0 0 0 ,防止其越界。
- 判断有效位数 n n n 与字符串的长度的大小,如果字符串位数大于有效位数则要进行截断,反之补 0 0 0 。
- 返回时,注意字符串的格式。
代码
#include<bits/stdc++.h>
using namespace std;
int n;
string a, b;
string change(string str, int n)
{
//找到'.',如果没有则加在后面并且找到其所在位置
int k = str.find(".");
if (k == -1) str += ".", k = str.find(".");
//合并'.'两边的字符串,并去除前缀0
string s = str.substr(0, k) + str.substr(k + 1);
while (s.size() && s[0] == '0') s = s.substr(1), k--;
if (s.empty()) k = 0; //字符串为空k也要置0
if (s.size() > n) s = s.substr(0, n); //字符串长度大于有效位要截断
else s += string(n - s.size(), '0'); //反之要补0
return "0." + s + "*10^" + to_string(k);
}
int main()
{
cin >> n >> a >> b;
a = change(a, n);
b = change(b, n);
if (a == b) cout << "YES " << a << endl;
else cout << "NO " << a << " " << b << endl;
return 0;
}