zoukankan      html  css  js  c++  java
  • [LeetCode] Palindrome Number

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

    click to show spoilers.

    Some hints:

    Could negative integers be palindromes? (ie, -1)

    If you are thinking of converting the integer to string, note the restriction of using extra space.

    You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

    There is a more generic way of solving this problem.

    两种方法:

    第一种:借助之前实现的reverse integer的方法,将int x reverse 得到 y,然后比较x,y是否相等,

    第二种:先得到x的base,注意,1231的base是10^3,然后1234/10^3得到1,和最后的1作比较,然后x=1234-1*1000 = 234,x=x/10=23,base=base/100=10,

        反复迭代,可以得到答案

     参考http://www.cnblogs.com/remlostime/archive/2012/11/13/2767676.html

    class Solution {
        public:
            int reverse(int x) {
                // Start typing your C/C++ solution below
                // DO NOT write int main() function
                int sign = x > 0 ? 1 : -1;
                long long y = abs(x);
    
                long long ret = 0;
                while(y)
                {   
                    int digit = y % 10; 
                    ret = ret * 10 + digit;
                    y /= 10; 
                    if(ret * sign > INT_MAX)
                        return 0;
                    if(ret * sign < INT_MIN)
                        return 0;
                }   
    
                return ret * sign;
            }   
    #if 0
            bool isPalindrome(int x) {
                if(x == 0)
                    return true;
                if(x <0)
                    return false;
                int y = reverse(x);
                if(x == y)
                    return true;
                else 
                    return false;
            }  
    #endif        
        bool isPalindrome(int x) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if (x < 0)
                return false;
            if (x < 10)
                return true;
                
            int base = 1;
            while(x / base >= 10)
                base *= 10;
                
            while(x)
            {
                int leftDigit = x / base;
                int rightDigit = x % 10;
                if (leftDigit != rightDigit)
                    return false;
                
                x -= base * leftDigit;
                base /= 100;
                x /= 10;
            }
            
            return true;
        }
    };
  • 相关阅读:
    小程序登录页面
    小程序环境搭建
    js闭包
    作用域和作用域链及预解析
    高阶函数
    在.net core项目中,增加gulp打包任务
    阿里云部署docker-swarm 内网问题
    .net identity scaffold
    c#中对XML反序列化
    c# Reactive Extension中的FromEventPattern和FromEvent
  • 原文地址:https://www.cnblogs.com/diegodu/p/4252967.html
Copyright © 2011-2022 走看看