ARTS leetcode3 Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true
Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

这道题的意思是判断输入的数是否是一个回文数字,什么叫回文数字,顺序和逆序得到是同一个值。

我的思路:
1.按照题目意思,先将数值逆序
2.然后将逆序前的值和逆序后的值对比,是否相等,如果相等返回true,否则返回false

关于逆序,有好多办法,
(1)转为字符串调用StringBuilder的reverse()方法逆序
(2)转为字符串,然后循环字符数组,前后对应位置交换元素得到新的字符数组,转为字符串,再次比较
(3)利用数学的思想来求余,除法计算等来形成新的数值,然后比较

我第一想法是(2),所以实现代码如下所示:

class Solution {
    public boolean isPalindrome(int x) {
        String num = String.valueOf(x);
        char[] ch = num.toCharArray();
        int right = ch.length-1;
        for(int left=0;left<ch.length/2;left++,right--){
            char temp = ch[left];
            ch[left] = ch[right];
            ch[right] = temp;
        }
        if(num.equals(new String(ch))){
            return true;
        }
        return false;
    }
}
Runtime: 8 ms
Memory Usage: 35.3 MB

思路1的解法:

class Solution {
    public boolean isPalindrome(int x) {
        StringBuilder sb=new StringBuilder(x+"");
    return sb.toString().equals(sb.reverse().toString());
    }
}
Runtime: 9 ms
Memory Usage: 36.2 MB

思路3的解法:

class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) return false;
        int ans = 0;
        int num = x;
        while ( num > 0) {
            ans = ans * 10 + num % 10;
            num = num / 10;
        }
        if (ans != x) return false;
        return true;
    }
}
Runtime: 6 ms
Memory Usage: 34.4 MB

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值