zoukankan      html  css  js  c++  java
  • 【leetcode】Palindrome Number (easy)

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

    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.

    思路:

    不能用额外的空间,数字还有可能过大。 处理方法是把数字截为两半,后半段翻转与前半段对比

    class Solution {
    public:
        bool isPalindrome(int x) {
            int y = 0; //把x的后半段反过来
            if(x > 0 && x % 10 == 0) //如果大于0的数字以0结尾 一定不是回文
                return false;
            if(x >= 0 && x < 10) //个位数一定是回文
                return true;
            while(y <= x)
            {
                if(y == x || (x / 10 > 0 && y == x / 10)) //偶数个数字 和奇术个数字都要考虑 
                    return true;
                y = y * 10 + x % 10;
                x = x / 10; //把x后面给y了的截掉
            }
            return false;
        }
    };

    同样思路,更简洁的代码:

    class Solution {
    public:
        bool isPalindrome(int x) {
            int i = 0;;
            if ((x % 10 == 0 && x != 0) || x < 0) return false;
            while (i < x) {
                i = i * 10 + x % 10;
                x = x / 10;
            }
            return (i == x || i / 10 == x);        
        }
    };
  • 相关阅读:
    Java语法总结 线程
    Java多线程编程总结
    eclipse插件开发
    Java私塾的一些基础练习题(一)
    反射练习
    内部类实现动态链表(增,删,查,打印)
    oracle 存储过程第四天
    java 面向对象个人理解
    jsp的flash小例子
    oralcle 存储过程批处理
  • 原文地址:https://www.cnblogs.com/dplearning/p/4273308.html
Copyright © 2011-2022 走看看