Leetcode 009 回文数

地址 https://leetcode-cn.com/problems/palindrome-number/

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

示例 1:

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

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

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

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

解答 

1 双指针经典用法

数字转换成字符串或者vector

然后使用双指针检测两头指针指向的元素是否相等 直到两者相遇

可以做点小优化  如果是负数就不用判断是不是回文数了 肯定不是 -1 -121 

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        string s = to_string(x);
        
        int l = 0; int r = s.size()-1;
        
        while(l <r){
            if(s[l] != s[r]) return false;
            l++;r--;
        }
        
        return true;
    }
};

如果不转化成字符串 那么久另外开个数字将原数字的元素逐个移出 加入新数字。

如果该数字是回文数 那么 两者正序逆序肯定相等。

同样做了负数直接判断false的优化

class Solution {
public:
    
    bool isPalindrome(int x) {
        if(x<0) return false;
        long long  tmp = 0;
        int copyx = x;
        while (copyx != 0) {
            int add = copyx % 10;
            copyx = copyx / 10;
            tmp += add;
            tmp *= 10;
        }

        if ( tmp/10  == x)
            return true;

        return false;

    }
    
};
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/13082932.html