#1060. Are They Equal【字符串处理】

原题链接

Problem Description:

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 × 1 0 5 0.123\times 10^5 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 N N, A and B B B, where N N N ( < 100 <100 <100) is the number of significant digits, and A A A and B B B are the two float numbers to be compared. Each float number is non-negative, no greater than 1 0 100 10^{100} 10100, and that its total digit number is less than 100 100 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 form 0.d[1]...d[N]*10^k (d[1] > 0 unless the number is 0); or NO 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

Problem Analysis:

  1. 找到小数点的位置,如果没有小数点,可以认为小数点在数字末尾

  2. 将小数点移动到最前面

  3. 移除前导零,并同时有效数字位数 k --

  4. 如果有效数字位数超过 n n n 位,那么就从 n n n 处截断,只保留 n n n 位;若不足 n n n 位,将有效数字补足 n n n 位

Code

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

string change(string a, int n)
{
    int k = a.find(".");
    if (k == -1) a += '.', k = a.find(".");
  
    string s = a.substr(0, k) + a.substr(k + 1);
    while (s.size() && s[0] == '0') s = s.substr(1), k -- ;
    
    if (s.empty()) k = 0;
    if (s.size() > n) s = s.substr(0, n);
    else s += string(n - s.size(), '0');
    
    return "0." + s + "*10^" + to_string(k);
}

int main()
{
    int n;
    string a, b;
    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;
}
上一篇:《CCNA学习指南:Cisco网络设备互连(ICND1)(第4版)》——2.6节TCP/IP协议栈


下一篇:云栖大会一年不到再度挥师江苏 阿里云啥算盘??