java回文数怎么编程

时间:2025-01-25 01:39:15 网络游戏

在Java中,可以通过以下几种方法来判断一个整数是否是回文数:

方法一:直接反转整数

```java

public class PalindromeNumber {

public static void main(String[] args) {

int number = 121;

if (isPalindrome(number)) {

System.out.println(number + " 是回文数");

} else {

System.out.println(number + " 不是回文数");

}

}

public static boolean isPalindrome(int number) {

if (number < 0) {

return false;

}

int reversed = 0;

int originalNumber = number;

while (number != 0) {

int lastDigit = number % 10;

reversed = reversed * 10 + lastDigit;

number = number / 10;

}

return originalNumber == reversed;

}

}

```

方法二:使用字符串反转

```java

import java.util.Scanner;

public class PalindromeNumber {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("请输入一个整数: ");

int number = scanner.nextInt();

if (isPalindrome(number)) {

System.out.println(number + " 是回文数");

} else {

System.out.println(number + " 不是回文数");

}

}

public static boolean isPalindrome(int number) {

String numStr = String.valueOf(number);

String reverseStr = new StringBuilder(numStr).reverse().toString();

return numStr.equals(reverseStr);

}

}

```

方法三:多循环判断

```java

public class Main {

public void Palindrome() {

for (int i = 1000; i < 10000; i++) {

String ans = Integer.toString(i);

String reverse = new StringBuffer(ans).reverse().toString();

if (ans.equals(reverse)) {

System.out.println(i);

}

}

}

public static void main(String[] args) {

new Main().Palindrome();

}

}

```

方法四:取余判断

```java

public class PalindromeNumber {

public static boolean isPalindrome(int x) {

int rev = 0;

int temp = x;

while (temp != 0) {

int digit = temp % 10;

rev = rev * 10 + digit;

temp = temp / 10;

}

return (x == rev || x == rev / 10);

}

public static void main(String[] args) {

int num = 12321;

if (isPalindrome(num)) {

System.out.println(num + " 是回文数。");

} else {

System.out.println(num + " 不是回文数。");

}

}

}

```

方法五:利用StringBuilder的reverse方法

```java

import java.util.Scanner;

public class PalindromeNumber {

public static void main(String[] args) {

System.out.println("请输入一个整数:");

int num = new Scanner(System.in).nextInt();

System.out.println("输入的数是否为回文数:" + isTrue(num));

}

public static boolean isTrue(int num) {

if (num < 0) {

return false;

}

int result = 0;

int temp = num;

while (temp != 0) {

result = result * 10 + temp % 10;

temp = temp / 10;

}

return num == result || num == result / 10;

}

}

```

以上方法各有优缺点,可以根据具体需求和场景选择合适的方法来实现。