SPOJ:PALIN-下一个回文:测试案例1的WA

时间:2019-06-30 16:47:58

标签: java string palindrome

该代码正在通过测试用例0,但为测试用例1提供了WA。请耐心等待,因为我几天以来一直在尝试此问题。

我使用String做到了,因为no不能有10e6位数字。

我已经尝试过spoj工具包或任何其他来源的所有测试用例。它们都给出正确的输出。

这是我的代码的链接: https://ideone.com/YqzFRn

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;

class Main {
    public static void main(String[] args) throws NumberFormatException, IOException {
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        while (t-- > 0) {
            String s = br.readLine();
            s = s.trim();
            if(s.charAt(0) == '0') {
                while(s.charAt(0) == '0')
                    s = s.substring(1);
            }
            if (all9(s)) {
                BigInteger b = new BigInteger(s);
                b = b.add(new BigInteger("2"));
                System.out.print(b);
                continue;

            }
            int i = 0, j = s.length() - 1;

            int mid = (i + j) / 2;

            String f = s.substring(0, mid + 1);
            String rev = rev((s.length() % 2 == 0) ? s.substring(0, mid + 1) : s.substring(0, mid));

            String ans = f + rev;

            while (ans.compareTo(s) <= 0) {
                ans = big(ans);
            }

            System.out.println(ans);

        }

    }

    private static boolean all9(String s) {
        // TODO Auto-generated method stub
        int i = 0;
        while (i < s.length()) {
            if (s.charAt(i) != '9')
                return false;
            i++;
        }
        return true;
    }

    private static String big(String ans) {
        int mid = ans.length() / 2;
        String s = "";
        String f = "";
        if (ans.length() % 2 == 0) {
            f = ans.substring(0, mid);
        } else {
            f = ans.substring(0, mid + 1);
        }
        BigInteger b = new BigInteger(f);
        b = b.add(new BigInteger("1"));
        s = s + b;
        String rev = rev((ans.length() % 2 == 0) ? s : s.substring(0, mid));
        ans = s + rev;

        return ans;
    }

    private static String rev(String s) {
        // TODO Auto-generated method stub
        return new StringBuilder(s).reverse().toString();
    }

}

0 个答案:

没有答案