LeetCode-回文数

题解

  这道题需要处理一个溢出的问题。如下是我第一次提交的代码,11509个测试用例可以通过11508个,是因为没有考虑到直接反向输出回文数值也许会导致溢出的问题,且程序耗时较长。

#include "iostream"
#include "vector"
#include "math.h"
using namespace std;
class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        vector<int>nums;
        int reverse_x=0;
        int tmp=x;
        while(x!=0)
        {
            nums.push_back(x%10);
            x=x/10;
        }
        int len=nums.size();
        for(int i=0,j=len-1;i<len;i++,j--)
        {
            int m=pow(10,j);
            reverse_x+=nums[i]*m;
        }
        if(reverse_x==tmp) return true;
        else return false;

    }
};

  官方题解方法很好的解决了溢出隐患和缩短了运行时间。为了避免溢出,考虑只反转int数字的一半,若后半部分反转后与原数字的前一半相同,则数字为回文数字。问题的关键在于如何知道反转的位数已经达到原始数字的一半了?处理方法是:每次反转一位数字原始数字都会除以10,反转后的数字会乘10,当原始数字不大于反转后的数字时,就意味着处理了一半位数。

  考虑几个特殊情况:

  1. 负数均不是回文数

  2. 以0结尾的数字,除了0都不是回文数

    #include “iostream”

    using namespace std;
    class Solution {
    public:
    bool isPalindrome(int x) {
    if(x<0 || x%10==0&&x!=0) return false;
    int reverse_x=0;

         while(x>reverse_x)
         {
             reverse_x=reverse_x*10+x%10;
             x=x/10;
         }
         // return (x==reverse_x || x==reverse_x/10 );
         if(x==reverse_x || x==reverse_x/10)
         return true;
         else
         return false;
     }
    

    };

  发现最后返回值时用if else用时8ms,超过96%代码,但是用题解中的return (x==reverse_x || x==reverse_x/10 );耗时16ms,超过70%代码。

#题解三

  转换为字符串,然后判断字符串的前后部分是否相等。

#include "iostream"
#include "string"
#include "math.h"
using namespace std;
class Solution {
public:
	bool isPalindrome(int x) {
    	if(x<0 || x%10==0&&x!=0) return false;
    	string str=to_string(x);
    	int len=str.length();
    	int mid=len%2==0?len/2:len-1/2;

    	for(int i=0;i<mid;i++)
    	{
        	if(str[i]=str[len-i])
        	return true;
    	}
    	return false;
	}
};

  这个程序没有通过提交,11509个测试用例通过11493个,0没通过,123没通过。来日再改。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值