您的当前位置:首页正文

Java判断回文数的2种方法

2024-11-24 来源:个人技术集锦

1.利用String类分割字符数组进行反转

2.利用StringBuffer类的reverse()方法

代码如下(示例):

package com.zhang.suanfa;

import java.util.Scanner;

public class HuiWen {
    public static void main(String[] args) {
        System.out.println(hui1());
        System.out.println(hui2());
    }

    // 方法1
    public static boolean hui1() {
        // 判断 回文数
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        char[] chars = s.toCharArray();
        int left = 0, right = chars.length - 1;
        while (left < right){
            if (chars[left] != chars[right]) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
    
    
    // 方法2
    public static boolean hui2(){
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        StringBuffer stringBuffer = new StringBuffer(s);
        return stringBuffer.reverse().toString().equals(stringBuffer.toString());
    }


}


输出

显示全文