力扣算法题(Leetcode)回文数判断

2 篇文章 0 订阅
2 篇文章 0 订阅

Leetcode算法学习之回文数判断【简单】

回文及回文数的定义

  • 回文(English:palindrome)是指正读反读都能读通的句子,它是古今中外都有的一种修辞方式和文字游戏,如“我为人人,人人为我”等。在数学中也有这样一类数字有这样的特征,成为回文数(palindrome number)。

    摘自百度《回文数》

  • 例如: n=1234321是回文数,n=1234567则不是

  • 注意:

    • 偶数个的数字也有回文数124421
    • 小数没有回文数
    • 负数没有回文数(根据题意)

题目要求

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文数,而 123 则不是。

  • 示例
    • input-> x=121; output-> true
    • input-> x=-121; output-> false
    • input-> x=10; output-> false
    • input-> x=-101; output-> false
  • 提示
  • − 2 31 < = x < = 2 31 − 1 \qquad -2^{31} <= x <= 2^{31} -1 231<=x<=2311

解题思路【一】自创

  • 创建数组并且将数字x每一位转化到数组中,同时创建接收反转后的数组
        char [] chars = String.valueOf(x).toCharArray();
        char [] chars1 = new char[chars.length];
  • for循环反转数组并用chars1数组接收
        for (int i = 0; i <= chars.length-1; i++) {
            chars1[i] = chars[chars.length - 1 - i];
        }
  • 把前后两个数组转化为字符串用字符串有关函数进行比较
        String str1 = new String(chars);
        String str2 = new String(chars1);
        boolean temp = str1.equals(str2) ? true:false;
        return temp;

解题思路【二】大神创

  • 首先排除负数
       if(x < 0)
           return false;
  • 用纯数学取位数的方法反转
       int cur = 0;
       int num = x;
       while(num != 0){
         cur = cur * 10 + num % 10;
         num /= 10;
       }
       return cur == x;

由于本人才疏学浅实在不明白这个方法是如何起作用的,如何构想出来的,以及内在逻辑和数据结构是怎样的,只能暂时照搬。求解释!!

代码附上仅供参考

  • 解法一
    public static boolean isPalindrome(int x) {

        char [] chars = String.valueOf(x).toCharArray();
        char [] chars1 = new char[chars.length];

        for (int i = 0; i <= chars.length-1; i++) {
            chars1[i] = chars[chars.length - 1 - i];
        }

        String str1 = new String(chars);
        String str2 = new String(chars1);
        boolean temp = str1.equals(str2) ? true:false;
        return temp;
    }
  • 解法二
    public static boolean isPalindrome(int x){
          if(x<0)
             return false;
          int cur = 0;
          int num = x;
          while(num != 0){
             cur = cur * 10 + num % 10;
             num /= 10;
       }
       return cur == x;
    }

欢迎大家批评指正!评论区见

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值