LeetCode:回文数

刷题神器:LeetCode官方网站

一、题目还原

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:
你能不将整数转为字符串来解决这个问题吗?

二、解题思路

Solution 1
① 利用整数反转进行比较
Solution 2
① 转换成字符串,用reverse函数进行比较

三、代码展示

① main函数

public static void main(String[] args) {
    int x = 12344321;
    System.out.println("isPalindrome == "+isPalindrome(x));
    System.out.println("isPalindrome2 == "+isPalindrome2(x));
}

② isPalindrome方法函数

public static boolean isPalindrome(int x){
    int s = x;
    if(x < 0){
        return false;
    }
    long result = 0;
    while(x > 0){
       result = result * 10 + x % 10;
       if(result > Integer.MAX_VALUE){
           return false;
       }
       x /= 10;
    }

    return s == (int)result;
}

控制台输出:

isPalindrome == true

Process finished with exit code 0

③isPalindrome2方法函数

public static boolean isPalindrome2(int x) {
   StringBuilder stringBuilder = new StringBuilder(x+"");
   if(stringBuilder.toString().equals(stringBuilder.reverse().toString())){
       return true;
   }
   return false;
}

控制台输出:

isPalindrome2 == true

Process finished with exit code 0
四、自我总结

本题是LeetCode第九题,难度为简单,涉及到的算法在之前 题目中都有涉及,算是巩固基础知识吧
Q9提交记录

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值