0

这是代码。我想提高代码的效率。

package palindrome;
import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class Palindrome {


    static Stack<Character> ss=new Stack<Character>();

    public static void main(String[] args) throws IOException {
        // TODO code application logic here


        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));

        String s[]=read.readLine().split(",");

        int min=Integer.parseInt(s[0]);
        int max=Integer.parseInt(s[1]);
        int finResult=palindrome(min,max);
        System.out.println(finResult);

    }


    public static int palindrome(int min,int max)
    {
        int result=0;
        for(int i=min; i<=max; i++)
        {
            String bin=BigInteger.valueOf(i).toString(2);
            if(check(bin))
            {
                result+=1;
            }

        }
        return result;
    }


    public static String fillStack(String input)
    {
        StringBuilder inn=new StringBuilder();
        for(int i=0; i<input.length(); i++)
        {
            char c= input.charAt(i);
            if(c!=' ')
            {
                ss.push(c);
                inn.append(c);
            }   
        }
        return inn.toString();
    }

    public static String buildReverse()
    {
        StringBuilder rev=new StringBuilder();

        while(!ss.empty())
        {
            char ch=ss.pop();
            rev.append(ch);
        }

        return rev.toString();
    }

    public static boolean check(String input)
    {
        if(fillStack(input).equalsIgnoreCase(buildReverse()))
            return true;
        else
            return false;
    }

}

当我使用像 (1,1000000) 这样的输入时,计算需要很长时间。所以我该如何限制

时间。否则我怎样才能提高这段代码的效率?

谢谢你。

4

1 回答 1

2

First, it doesn't seem you want to reduce compile, but runtime. Second, if you just want to check if a number formatted as a string is a palindrom, simply reverse your already created string and compare reversed and original.

https://stackoverflow.com/a/7569370/2055163

http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html#reverse()

于 2013-10-26T07:36:06.867 回答