LeetCode9.回文数

原题链接:https://leetcode-cn.com/problems/palindrome-number/

9. 回文数

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:
输入: 121
输出: true

示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

进阶:你能不将整数转为字符串来解决这个问题吗?

思路

(1)字符串
将输入数字转换为字符串,循环对称判断字符串两端是否相同,如不同则返回false,循环完成后,返回true

(2)数学方法
每次取输入数字的首尾数字,循环判断是否相等,如不等则返回false,循环完成后,返回true

代码实现

(1)字符串方法

import java.util.Scanner;

public class IsPalindrome_toString {

    public static boolean isPalindrome(int x) {
        if (x<0 || (x%10==0 && x!=0)) return false;
        if (x<10) return true;

        StringBuilder sb = new StringBuilder(x+"");

        String s = sb.toString();
        for (int i = 0; i < s.length()/2; i++) {
            if (s.charAt(i) != s.charAt(s.length()-i-1)) return false;
        }

        return true;

    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        System.out.println(isPalindrome(Integer.parseInt(input)));
    }
}

(2)数字方法

import java.util.Scanner;

public class IsPalindrome {
    public static boolean isPalindrome(int x){
        if (x<0) return false;
        if (x<10) return true;

        int temp = x;
        int count = 0; //位数
        while (temp!=0){
            count++;
            temp/=10;
        }

        int a = (int) Math.pow(10,count-1);
        for (int i = 0; i < count/2; i++) {
            int j = x%10; //尾位数
            int k = x/a;  //首位数
            if (j!=k) return false;
            x -= k*a;
            a/=100;
            x/=10;
        }


        return true;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        System.out.println(isPalindrome(Integer.parseInt(input)));
    }
}
总结

1.字符串方法较为简单,但性能较低,需要注意的是根据数字构造字符串时,不可忘记数字后面的 +""

StringBuilder sb = new StringBuilder(x+"");

2.数字方法也不难,考虑好如何准确取到首位和末位数字即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值