【Java学习】16数据结构篇之回文数的判断

参考:leetcode num:009

package num009;

import java.util.Scanner;

public class Num009Demo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        Solution num009 = new Solution();
        boolean B = num009.isPalindrome01(x);
        boolean C = num009.isPalindrome02(x);
        boolean D = num009.isPalindrome03(x);
        boolean E = num009.isPalindrome04(x);
        System.out.println(E);
    }
}
class Solution {
    public boolean isPalindrome01(int x) {
        //转换为字符转,字符串翻转和比较
        String str1 = new StringBuilder(x+"").reverse().toString();
        String str2 = x + "";
        return str1.equalsIgnoreCase(str2);
    }

    public boolean isPalindrome02(int x) {
        //将整数的个位与最高位、十位与正数第二位、等等依次进行比较
        if((x/10)>0){
            int i = 0;
            int y = x;
            while((y/10)>0){i=i+1;y=y/10;}
            int left = 0;
            int right = 0;
            for(int j = 0; (2*j)<i;j++){
                if(left == right){
                    left = x/(10^(i-j));
                    right = x%(10^(j+1));
                }else{
                    return false;
                }
            }
            return true;
        }else{
            return x > 0;
        }
    }

    public boolean isPalindrome03(int x) {
        //将整数整体翻转后,与原始数据进行比较
        int newrevers = 0 ;
        int y = x;
        if(x/10>0){
        while(x/10>0){
            newrevers = newrevers*10 + x%10;
            x = x/10;
        }
        return newrevers==(y/10);
        }else {
            return x>0;
        }
    }

    public boolean isPalindrome04(int x) {
        //在03算法基础上采用折中对比
        if(x<0){
            return false;
        }
        int newrever = 0;
        while(x>newrever){
            newrever = newrever*10+(x%10);
            x = x/10;
        }
        return x == newrever || x==newrever/10;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值