[LeetCode] #9 Palindrome Number

来源:互联网 发布:诸葛恪 淘宝 编辑:程序博客网 时间:2024/06/07 01:46


好久没有刷题了,现在开始刷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 NumberDescription: https://leetcode.com/problems/palindrome-number/Author: MummyDingDate : 2015-12-27Run 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 NumberDescription: https://leetcode.com/problems/palindrome-number/Author: MummyDingDate : 2015-12-28Run 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