<找工作>C++回文数

<找工作>C++回文数,第1张

<找工作>C++回文

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

1、笨解法:存储每一位,再逐位比较

class Solution {
public:
    bool isPalindrome(int x) {
        vector mw(100);
        int i = 0, j = 0;
        if(x < 0)
            return false;
        else
        {   if(x==0)
                return true;
            else{
                while(x > 0)
                {
                    mw[i] =  x % 10;
                    x = x/10;
                    i++;
                }
                for(j=0; j <= (i-1)/2; j++)
                {
                    if(mw[j]!=mw[i-1-j])
                        return false;
                }
                return true;
            }
        }

    }
};

2、比较回文数和逆回文数是否相等。为了避免移除问题,只比较一半。是否一半的判断是x>RevertNumber

class Solution {
public:
    bool isPalindrome(int x) {
        int RevertNumber = 0;
        int tmp = 0;
        if(x < 0 || ( x!=0 && x%10==0))
            return false;
        else
        {   if(x==0)
                return true;
            else
            {
                while(x > RevertNumber)
                {
                    tmp =  x % 10;
                    x = x/10;
                    RevertNumber = RevertNumber*10 + tmp;
                }
                return x == RevertNumber || x == RevertNumber/10;
            }
        }

    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5714061.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存