zoukankan      html  css  js  c++  java
  • LeetCode 9. Palindrome Number

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

    判断一个数是否是回文数,不能用额外的空间

    我第一次做的时候,没有考虑到不能用额外的空间(空间复杂度为(n)),用了一个字符串来保存数字,而且题目的设定是

    负数不是回文数

    class Solution {
    public:
        bool isPalindrome(int x) {
            string s;
            if(x<0)return false;
            while (x)
            {
                s.push_back(x % 10+48);
                x /= 10;
            }
            for (int i = 0;i < (int(s.size()) - 1 - i);++i)
            {
                if (s[i] != s[s.size() - 1 - i])return false;
            }
            return true;
        }
    };

    下面是改进的方法:空间复杂度为O(1)

    class Solution {
    public:
        bool isPalindrome(int x) {
            if (x < 0)return false;
            if(0==x)return true;
            int div = 1000000000;
            int cnt=10;
            for (;!(x / div);div /= 10,--cnt);
            cnt=cnt/2;
            while (x&&cnt--)
            {
                if (x / div%10 != x % 10)return false;
                div /= 100;
                x /= 10;
                if(x<10)return true;
            }
            return true;
        }
    };
  • 相关阅读:
    元数据管理
    sqoop 安装
    postgres 索引
    postgres 表和库等信息大小统计
    Perl基础语法
    Perl 认识简介
    Oracle层次查询start with connect by
    jquery.cookie.js 的使用指南
    JavaScript中cookie使用
    CSS实现垂直居中的4种思路
  • 原文地址:https://www.cnblogs.com/csudanli/p/5885998.html
Copyright © 2011-2022 走看看