我需要编写一个程序,找到作为输入提供的两个整数之间的所有回文完美正方形,但不包括提供的输入。
当您输入大量输入时,我的程序会被“杀死”,即10000和100000.我该如何解决这个问题?
import static java.lang.Math.sqrt;
import java.util.Scanner;
public class PalinPerfect {
public static void main(String[] args){
Scanner user_input = new Scanner(System.in);
String start_point;
System.out.print("Enter start point N:\n");
start_point = user_input.next();
int start = Integer.parseInt(start_point);
String finish_point;
System.out.print("Enter ending point M:\n");
finish_point = user_input.next();
int finish = Integer.parseInt(finish_point);
System.out.print( "The palindromic perfect squares are as follows:\n");
for(int i=start; i <=finish; i++){
int a,n1,n2=0;
n1=i;
for(a = 0; a <= i; a++) {
if (a==Math.sqrt(n1)) {
n2=n1;
}
}
int number = n2;
int reversedNumber = 0;
int temp=0;
while(number > 0){
temp = number % 10;
number = number / 10;
reversedNumber = reversedNumber * 10 + temp;
}
if(n1 == reversedNumber)
System.out.println(n1);
}
}
}
答案 0 :(得分:1)
sqrt
是一项昂贵的操作,而且您经常使用它。另一种方法是完全相反:计算数字的平方,如果它在范围内,看它是否是回文。
当然,这种方法运行得更快:
public static void main(String[] args){
Scanner user_input = new Scanner(System.in);
String start_point;
System.out.print("Enter start point N:\n");
start_point = user_input.next();
int start = Integer.parseInt(start_point);
String finish_point;
System.out.print("Enter ending point M:\n");
finish_point = user_input.next();
int finish = Integer.parseInt(finish_point);
System.out.print( "The palindromic perfect squares are as follows:\n");
for(int i = (int)Math.ceil(Math.sqrt(start)); i * i <= finish; i++){
int number = i * i;
int reversedNumber = 0;
int temp = 0;
while(number > 0){
temp = number % 10;
number = number / 10;
reversedNumber = reversedNumber * 10 + temp;
}
if(i * i == reversedNumber)
System.out.println(reversedNumber);
}
}
答案 1 :(得分:1)
这是打印回文平方数的另一种简单而简洁的方法。
确保首先检查isPalindrome操作,然后才检查 isPerfectSquare。
System.out.print("The palindromic perfect squares are as follows:\n");
for (int i = start + 1; i < finish; i++) {
if (isPalindrome(i) && isPerfectSquare(i) ) {
System.out.println(i);
}
}
定义isPerfectSquare&amp; isPalindrome方法如下
static boolean isPerfectSquare(int input) {
int SquareRoot = (int) Math.sqrt(input);
return ((SquareRoot * SquareRoot) == input);
}
static boolean isPalindrome(int input) {
String str = Integer.toString(input);
return new StringBuffer(str).reverse().toString().equals(str);
}