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;
        }
    };
  • 相关阅读:
    t
    溢出
    https://stackoverflow.com/questions/45591594/fetch-does-not-send-headers
    显示在用户屏幕上的缩略图
    cache buffer
    LZW
    t
    指针悬挂
    使用Linux服务器来通过网络安装和激活Windows 7 —— 一些基本原理
    在C++中如何动态分配一个二维数组
  • 原文地址:https://www.cnblogs.com/diegodu/p/4252967.html
Copyright © 2011-2022 走看看