Home > Java > javaTutorial > body text

How to determine whether it is a palindrome number in java

爱喝马黛茶的安东尼
Release: 2019-12-27 15:42:35
Original
13916 people have browsed it

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 + "是回文数");  
    }  
}  
}
Copy after login

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("不是回文");
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template