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;
        }
    };
    

      

  • 相关阅读:
    利用mybatis-generator自动生成代码
    gradle安装
    有关﹤![CDATA[ ]]> 说明
    mysql时间字段转换为毫秒格式
    string 与BigDecimal互转
    VLOOKUP多条件查找不使用辅助列
    BIEE-CSS样式大全
    VBA【遍历每个工作表并将工作表表名赋予B2单元格】
    深入理解公式{1,0}的用法
    DB2解锁
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3412704.html
Copyright © 2011-2022 走看看