Home  >  Article  >  Java  >  How to determine whether it is a palindrome number in java

How to determine whether it is a palindrome number in java

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-12-27 15:42:3513915browse

How to determine whether it is a palindrome number in java

1. Use the reverse() method of StringBuilder to reverse the string to determine the number of palindromes.

//回文数:是一种数字。如:98789, 这个数字正读是98789,倒读也是98789  
//正读倒读一样,所以这个数字就是回文数  
import java.util.Scanner;  
public class HuiWenShu {  
public static void main(String[] args) {  
    Scanner sc = new Scanner(System.in);  
    System.out.println("请输入一个整数:");  
    int num = sc.nextInt();  
    String str1 = num + "";  
    // String str1 = Integer.toString(num);  
    // String str1 = String.valueOf(num);  
    StringBuilder str2 = new StringBuilder(str1);  
    str2.reverse();  
    int count = 0;  
    for (int i = 0; i < str1.length(); i++) {  
        if (str1.charAt(i) != str2.charAt(i)) {  
            System.out.println(str1 + "不是回文数");  
            break;  
        } else {  
            count++;  
        }  
    }  
    if (count == str1.length()) {  
        System.out.println(str1 + "是回文数");  
    }  
}  
}

2. By taking the modulo of the integer, invert the integer and finally judge.

Scanner in = new Scanner(System.in);
        System.out.println("请输入一个整数N=:");
        int input = in.nextInt();
        int i = 0;
        int sum = 0;
        int record=input;
        while(true){
            i = input%10;
            sum =sum*10+i;
            input /= 10;
            if(input==0) break;
        }
        if(sum==record)System.out.println("是回文");
        else System.out.println("不是回文");

PHP Chinese website has a large number of free JAVA introductory tutorials, everyone is welcome to learn!

The above is the detailed content of How to determine whether it is a palindrome number in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn