⬆︎
×

[PAT-A] 1060 Are They Equal

Hyplus目录

Java

测试点6错误,原因不明

import java.util.Scanner;

public class Main {
    static int n;

    public static void convert(StringBuilder s) {
        int k = 0;
        while (k < s.length() && s.charAt(k) != '.') {
            k++;
        }

        // If '.' is not found, append it at the end
        if (k == s.length()) {
            s.append('.');
        } else {
            // Remove the dot from its current position
            s.deleteCharAt(k);
        }

        // Remove leading zeros
        while (s.length() > 0 && s.charAt(0) == '0') {
            s.deleteCharAt(0);
            k--;
        }

        // Pad with zeros to match length n
        while (s.length() < n) {
            s.append('0');
        }

        // Trim to length n
        s.setLength(n);

        // Check if the number is zero after conversion
        double num = Double.parseDouble(s.toString());
        if (num == 0) {
            k = 0;
        }

        // Format the result string
        s.insert(0, "0.");
        s.append("*10^" + k);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        String a = scanner.next();
        String b = scanner.next();

        StringBuilder sa = new StringBuilder(a);
        StringBuilder sb = new StringBuilder(b);

        convert(sa);
        convert(sb);

        if (sa.toString().equals(sb.toString())) {
            System.out.println("YES " + sa.toString());
        } else {
            System.out.println("NO " + sa.toString() + " " + sb.toString());
        }

        scanner.close();
    }
}

C++

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

using namespace std;

int n;
string a, b;

void convert(string &s) {
    int k = 0;
    while (k < s.size() && s[k] != '.') k++;

    if (find(s.begin(), s.end(), '.') == s.end()) s += '.';
    s = s.substr(0, k) + s.substr(k + 1);
    while (s[0] == '0') s = s.substr(1), k--;

    while (s.size() < n) s += '0';
    s = s.substr(0, n);
    if (stod(s) == 0) k = 0;
    s = "0." + s + "*10^" + to_string(k);
}

int main() {
    cin >> n >> a >> b;
    convert(a);
    convert(b);

    if (a == b) cout << "YES " << a << endl;
    else cout << "NO " << a << " " << b << endl;

    return 0;
}

发表评论