[LeetCode] #9 Palindrome Number


好久没有刷题了,现在开始刷LeetCode 

GitHub : https://github.com/MummyDing/LeetCode

Source : https://leetcode.com/problems/palindrome-number/

Description :

Determine whether an integer is a palindrome. Do this without extra space.


题解:  题目描述非常简单,就是判断一个整数是否为回文数,但是有一个要求,不能使用额外的内存. 开始看到这题我还真以为一丁点多余的内存都不能使用,但是判断它是否回文要么首先反转再比较,要么知道位数一位一位比较. 如果一丁点多余的内存都不能又,那前者肯定不行,于是我考虑后面的情况,首先要求出位数,这个简单,但是位数怎么保存是个问题.我的解决方法是将原数字扩大十倍,将位数存储到各位.就这样,没有花费额外的储存空间写了一个解决方法.提交 WA,很显然,是超出整形范围了. 后来才知道,它这里指的花费多余存储是想不使用 字符串 数组 之类的东西,多几个变量是没关系的.理解这点后,我给出了一下解法:

/*
Problem: Palindrome Number
Description: https://leetcode.com/problems/palindrome-number/
Author: MummyDing
Date : 2015-12-27
Run Time: 156 ms
*/

#include <iostream>

using namespace std;

class Solution {
public:
    bool isPalindrome(int x) {
        int count = 1,tmpX = x;
        if(x < 0) return false;
        if(x < 10) return true;

        while(tmpX >= 10){
            tmpX /= 10;
            count ++;
        }
        for(int i = 0 ; i<count/2 ;i++){
            if((x/pow10(count-i-1))%10 != (x/pow10(i))%10)
            return false;
        }
        return true;
    }
    int pow10(int p){
        int sum = 1;
        while(p){
            sum *=10;
            p--;
        }
        return sum;
    }
};


花费了156 ms ,平均水平都没达到,效率太低.

再换

/*
Problem: Palindrome Number
Description: https://leetcode.com/problems/palindrome-number/
Author: MummyDing
Date : 2015-12-28
Run Time: 84 ms
*/

#include <iostream>

using namespace std;

class Solution {
public:
    bool isPalindrome(int x) {
       if(x < 0 ) return false;
       if(x < 10) return true;
       if(x %10 ==0 ) return false;
       int reverseX = 0 , tmpX = x;
       while(tmpX){
            reverseX =  reverseX * 10 + tmpX %10;
            tmpX /= 10;
       }
       if(reverseX == x) return true;
       return false;
    }
};

84 ms 只有之前一半多点,平均水平之上.

思路: 一位数 负数 什么的直接可以判断了. 否则再看各位数是否为0,为0 肯定不是. 最后将数字反转即可判断是否回文.

84ms 还没进入前30%,但是暂时没有想到可以再优化的地方,看到最快的有 64 ms 的. 我用Java字符串做,13ms(显然违规lol)





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值