我是Java的新手,我需要完成这个程序来检查整数是否是回文。请帮忙。
public static void main(String args[]){
System.out.println("Please enter an integer : ");
int integer = new Scanner(System.in).nextInt();
if(isPalindrome(integer)){
System.out.println(integer + " is a palindrome");
}else{
System.out.println(integer + " is not a palindrome");
}
}
答案 0 :(得分:9)
public static boolean isPalindrome(int integer) {
int palindrome = integer;
int reverse = 0;
// Compute the reverse
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// The integer is palindrome if integer and reverse are equal
return integer == reverse; // Improved by Peter Lawrey
}
高级解决方案:(由Shadov提供)
public static boolean isPalindrome(int integer) {
String intStr = String.valueOf(integer);
return intStr.equals(new StringBuilder(intStr).reverse().toString());
}
参考:http://www.java67.com/2012/09/palindrome-java-program-to-check-number.html#ixzz4emXfiD7V
请不要在下次没有工作的情况下提出问题。
答案 1 :(得分:1)
public static boolean isPalindrome(int number) {
int palindrome = number; // copied number into variable
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// if original and reverse of number is equal means
// number is palindrome in Java
if (number == reverse) {
return true;
}
return false;
}
来源:http://www.java67.com/2012/09/palindrome-java-program-to-check-number.html#ixzz4emXfiD7V
但你需要在这里明确没有提出作业问题。