zoukankan      html  css  js  c++  java
  • 9. Palindrome Number (JAVA)

    Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

    Example 1:

    Input: 121
    Output: true
    Example 2:

    Input: -121
    Output: false
    Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
    Example 3:

    Input: 10
    Output: false
    Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
    Follow up:

    Coud you solve it without converting the integer to a string?

    法I:逐一比较最左端与最右端的数字

    class Solution {
        public boolean isPalindrome(int x) {
            if(x<0) return false;
            
            int left; //the first bit of the inteter
            int right; //the last bit of the integer
            int divisor = 1; //divisor of each iteration
            int tmp = x;
            
            //determine the initial value of divisor
            while(x/divisor >= 10){
                divisor *= 10;
            }
            
            //check palindrome
            while(x>0){
                left = x/divisor; //divided by divisor to get the first bit
                right = x%10; //mod 10 to get the last bit
                if(left != right) return false;
                
                x = (x%divisor)/10; //mode divisor to remove the first bit, divided by 10 to remove the last bit
                divisor /= 100;
            }
            return true;
        }
    }

    数字问题注意:

    1. 负数

    2. 变换后 以0开始 (本题中,如10101)这种情况,除以divisor = 0,mod 10 = 最后那位。

        有多少个0,就得经过多少次循环,才能使得divisor的长度和被除数相等。在长度不等的时候,没次都循环末尾需为0,才能符合Palindrome的判断。所以该算法仍然可以验证有0开头的情况。

    法II:逆向思维,如果是parlindrome,那么求出的反转数应等于x

    这个方法的优点:只遍历了整数长度的一半。

    class Solution {
        public boolean isPalindrome(int x) {
            if(x<0 //negative number
               || (x%10 == 0 && x != 0)) //the check"x == reverseNum/10" has one exception: reverseNum is one-bit number but x isn't, this case only exist in x%10 == 0 && x != 0
                return false; 
            
            int reverseNum = 0;
            while(x > reverseNum){
                reverseNum = reverseNum * 10 + x%10;
                x /= 10;
            }
            if(x == reverseNum || x == reverseNum/10) return true; //check parlindrome of number with odd or even length
            else return false;
        }
    }

    parlindrome问题注意:

    1. 数字长度单、双分开讨论

  • 相关阅读:
    (转)一篇教会你写90%的shell脚本
    (转)printf命令详解
    (转)linux shell 字符串操作详解 (长度,读取,替换,截取,连接,对比,删除,位置 )
    (转)Shell中read的选项及用法
    (转)linux中shell变量$#,$@,$0,$1,$2的含义解释/Shell中的${}、##和%%使用范例/export
    (转)linux运维人员必会的22道shell编程面试题及视频讲解
    (转)李文周的博客
    ROS报错“An error occurred during the signature verification”的解决办法
    RRT and RRT Variants
    ROS LocalPlanner 基于自行车模型的DWA
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10757899.html
Copyright © 2011-2022 走看看