所以我正在创建一个基于this项目制作回文数字的程序。我的程序适用于较小的数字,但整数只能计算少量数字,因此我将必要的整数更改为BigInteger()。在做完这个之后,我遇到了一些我不太确定的问题。有人会对如何使这项工作有任何建议吗?
public class Main {
public static final boolean DEBUG = false;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//gets the number from the console
int number = input.nextInt();
if(DEBUG) System.out.println("Got your number!");
if(DEBUG) System.out.println("Bout to makePalendrome!");
makePalendrome(number);
}
public static boolean isPalendrome(BigInteger number){
String numberString = number.toString();
for(int i = 0; i < numberString.length(); i++){
if(numberString.charAt(i) != numberString.charAt(numberString.length() - 1 - i)) return false;
}
return true;
}
public static void makePalendrome(int input){
int steps = 0;
BigInteger number = new BigInteger((input + ""));
if(isPalendrome(number)) printResult(input, steps, number);
while(!isPalendrome(number)){
String numberString = number.toString();
String reversed = "";
for(int i = 0; i < numberString.length(); i++){
reversed += numberString.charAt(numberString.length() - 1 - i);
}
BigInteger numReversed = new BigInteger(reversed);
number.add(numReversed);
steps++;
}
printResult(input, steps, number);
}
public static void printResult(int number, int steps, BigInteger palendrome){
System.out.printf("The number %d becomes palendromic after %d steps, and becomes the number: %d%n", number, steps, palendrome);
System.exit(0);
}
}
答案 0 :(得分:5)
您的代码进入无限循环while(!isPalendrome(number))
因为,
number.add(numReversed);
这不会改变number
的值。您需要将其分配回来。
number= number.add(numReversed);