【leetcode刷题笔记】009.Palindrome Number

日期:20180912
题目描述:

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

详解:

新开了一个数组,把每一位存起来,思路很简单,代码如下:

class Solution {
public:
    bool isPalindrome(int x) {
        int a[10];
        bool isneg = false,res = true;
        if(x<0){
            return false;
        }
        int i = 0;
        for(;x!=0;i++){
            a[i] = x%10;
            x /= 10;
        }
        int j = 0;
        i--;
        while(j<i){
            if(a[j]!=a[i]){
                res = false;
            }
            j++;
            i--;
        }
        return res;
    }
};

最后我的用时256ms,最靠前的代码112ms,那究竟是怎么实现的呢。

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

新建了一个变量,通过循环,让它等于x的反转,然后判断它和x是不是相等。我怎么就没想到,一定是因为我一边喝酒一边写代码。


008_01.jpg
008_02.jpg
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.背景 最近要做PHP相关的项目,所以就提前在本地搭建Drupal环境,搭建采用最新Drupal8,php70,...
    zhjwang阅读 724评论 0 0
  • 复联三,过去了。电影中,我印象最深刻的,是灭霸那句,知识的诅咒。影片中,是两个人有这个荣幸。灭霸和钢铁侠。同样是为...
    星宇_c4a1阅读 239评论 0 0
  • 高山子阅读 228评论 0 1
  • 栀子花开放的季节里,往往轻轨出站口,地下商场进口,都会有人背着小背篓卖栀子花,因住在较暗的房间里面,虽说不上潮湿,...
    小爬杨阅读 189评论 0 1
  • 是秋,大殿外的雨又淅淅沥沥的下了起来,天依旧像褪不去的浓墨一样灰沉沉的,而大殿里的气氛也如同外面的天气一样阴沉得很...
    六月申阅读 856评论 2 15