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" might overflow,作为此题不必考虑,因为回环数翻转后还是它本身,既然原来没有溢出,翻转后也不会溢出。

    class Solution {
    public:
        bool isPalindrome(int x) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
    		if(x<0) return false;
    		int m=x;
    		int n=0;
    		while(m)
    		{
    			n=n*10+m%10;
    			m=m/10;
    		}
    		if(n==x) return true;
    		else return false;
        }
    };
    

      在这里http://www.cnblogs.com/remlostime/archive/2012/11/14/2770624.html发现了一个更好的办法。每次,取出数的最高位和最低位比较,设置一个base为10^n,用来取出数的最高位,每次循环除以100,因为每次数会消去2位。

    class Solution {
    public:
        bool isPalindrome(int x) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if (x < 0)
                return false;
            if (x == 0)
                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;
        }
    };
    

      

  • 相关阅读:
    UVA 12657 Boxes in a Line 双向链表模拟
    C语言单片和C#语言服务器端DES及3DES加密的实现
    关于TcpClient,Socket连接超时的几种处理方法
    拿来参考的学习计划
    faire la course
    今日法语2
    炸鱼
    今日法语
    今日疑问
    下周想做的菜
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3412704.html
Copyright © 2011-2022 走看看