美文网首页程序员
leetcode—9. 回文数

leetcode—9. 回文数

作者: 雪落无声听雨声 | 来源:发表于2020-07-29 00:12 被阅读0次

    问题描述

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

    示例 1:

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

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

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

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

    解决方案

    第一种 使用递归,转换成字符

    
    class Solution {
        public boolean isPalindrome(int x) {
            if(x<0) 
                return false;
            return help(x+"");
        }
        
        public boolean help(String temp){
            if(temp.length()<=1)
                return true;
            if(temp.charAt(0) != (temp.charAt(temp.length()-1))){
                return false;
            }else{
                return help(temp.substring(1,temp.length()-1));
            }
        }
    }
    
    image.png

    第二种 不用字符串 数字反转比较

    将整个数字反转过来,然后判断和原来的是否相等。

    class Solution {
        // 如果是 负数直接返回false
        //
        public boolean isPalindrome(int x) {
            if(x<0)
                return false;
            
            int temp = x;
            int result =0;
            while(temp>0){
                int index =temp%10;
                result = result*10 + index;
                temp /=10;
            }
            return  result==x?true:false;
        }
    }
    

    最大值 2147483648 0x7fff ffff

    最小值 -214783467 0x8000 0000

    image.png

    相关文章

      网友评论

        本文标题:leetcode—9. 回文数

        本文链接:https://www.haomeiwen.com/subject/cmecrktx.html