zoukankan      html  css  js  c++  java
  • 乘风破浪:LeetCode真题_009_Palindrome Number

    乘风破浪:LeetCode真题_009_Palindrome Number

    一、前言

       如何判断一个整型数字是回文呢,我们可能会转换成String来做,但是还有更简单的方法。

    二、Palindrome Number

    2.1 问题理解

    2.2 问题分析和解答

        通过题意我们知道不使用String来作答,因此我们想到可不可以采用取整和取余的运算来解决呢,如果将整数倒过来,余数乘以10加上更高位的数字,这样得到的数字如果和原来的数字相等,并且不是负数,那么就是回文的。这是我们的想法,但是是否有更好的方法呢,那就是如果是回文的,那么一半倒过来和另一半也是相等的,并且考虑到奇偶问题,这样就能减少一半的运算了。

        首先看官网上的解答:

    public class Solution {
        public bool IsPalindrome(int x) {
            // Special cases:
            // As discussed above, when x < 0, x is not a palindrome.
            // Also if the last digit of the number is 0, in order to be a palindrome,
            // the first digit of the number also needs to be 0.
            // Only 0 satisfy this property.
            if(x < 0 || (x % 10 == 0 && x != 0)) {
                return false;
            }
    
            int revertedNumber = 0;
            while(x > revertedNumber) {
                revertedNumber = revertedNumber * 10 + x % 10;
                x /= 10;
            }
    
            // When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
            // For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
            // since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
            return x == revertedNumber || x == revertedNumber/10;
        }
    }
    

         下面是我们自己的解答:

    public class Solution {
        /**
         * 原题
         * Determine whether an integer is a palindrome. Do this without extra space.
         *
         * 题目大意
         * 判断一个数字是否是回文数字,不要使用String转换。
         *
         * 解题思路
         *  首先,负数不是回文数字,其次对数字进行逆转,123变成321这样,如果变换后的数字相等说明是回文数字。
         */
        public boolean isPalindrome(int x) {
    
            // 负数不是回文数字
            if (x < 0) {
                return false;
            }
    
            // 数字逆转后的值,为了不使用溢出采用long
            long reverse = 0;
            int tmp = x;
    
            // 求逆转后的值
            while (tmp != 0) {
                reverse = reverse * 10 + tmp % 10;
                tmp /= 10;
            }
    
            // 判断是否是回文数字
            return x == reverse;
        }
    }
    

         因为这样做浪费了一半的计算资源,所以效率比较低。

    三、总结 

         通过一件事情,我们可以发现自己想到的并不是最优的,这个时候就要仔细想想是不是可以继续优化,优化的时候一定是利用了问题的某种特性,比如回文字符串的对称性。

  • 相关阅读:
    ubuntu下查看环境变量
    ubuntu关闭自动更新、打开 ubuntu 的 apport 崩溃检测报告功能
    Ubuntu 配置AP总结
    ubuntu 12.04亮度无法调节和无法保存屏幕亮度解决办法(echo_brightness)
    Ubuntu 13.04 双显卡安装NVIDIA GT 630M驱动
    Linux下添加硬盘,分区,格式化详解
    Eclipse启动分析
    “蚁族” 的生活方式画像
    Ubuntu下的防火墙
    Ubuntu下的杀毒
  • 原文地址:https://www.cnblogs.com/zyrblog/p/10210541.html
Copyright © 2011-2022 走看看