LeetCode:Palindrome Number - 回文数

一、题目名称java

Palindrome Number(回文数)ui

二、题目地址this

https://leetcode.com/problems/palindrome-numberspa

三、题目内容.net

英文:Determine whether an integer is a palindrome. Do this without extra space.code

中文:确认一个整数是不是回文数blog

四、解题方法1leetcode

将数字翻转后判断与原数字是否相等,能够参考LeetCode第7题(Reverse Integer)的解题思路。Java代码以下:开发

/**
 * 功能说明:LeetCode 9 - Palindrome Number
 * 开发人员:Tsybius
 * 开发时间:2015年9月24日
 */
public class Solution {
    
    /**
     * 判断某数是否为回文数
     * @param x 数字
     * @return true:是,false:否
     */
    public boolean isPalindrome(int x) {
        
        //负数不能为回文数
        if (x < 0) {
            return false;
        }
        
        //反转数字观察是否相等
        if (x == reverse(x)) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 反转数字
     * @param x 被反转数字
     * @return 反转后数字
     */
    public int reverse(int x) {
        
        long result = 0;

        while (x!=0) {
            result = result * 10 + x % 10;
            x /= 10;
        }
        
        return (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) ? 0 : (int)result;
    }
}

五、解题方法2字符串

另外一个方法是将数字转换为字符串,再经过StringBuilder类反转字符串,判断两字符串相等。Java代码以下:

/**
 * 功能说明:LeetCode 9 - Palindrome Number
 * 开发人员:Tsybius
 * 开发时间:2015年9月24日
 */
public class Solution {
    
    /**
     * 判断某数是否为回文数
     * @param x 数字
     * @return true:是,false:否
     */
    public boolean isPalindrome(int x) {

        if (x < 0) return false;
        if (x < 10) return true;
        
        String str1 = String.valueOf(x);
        String str2 = (new StringBuilder(str1)).reverse().toString(); 
        
        if (str1.equals(str2)) {
            return true;
        } else {
            return false;
        }
    }
}

六、解题方法3

还有一个方法,就是直接转换为字符串,而后再分别对字符串对称位置字符进行比较。Java代码以下:

/**
 * 功能说明:LeetCode 9 - Palindrome Number
 * 开发人员:Tsybius
 * 开发时间:2015年9月24日
 */
public class Solution {
    
    /**
     * 判断某数是否为回文数
     * @param x 数字
     * @return true:是,false:否
     */
    public boolean isPalindrome(int x) {

        if (x < 0) return false;
        if (x < 10) return true;
        
        String str = String.valueOf(x);
        for (int i = 0; i < str.length() / 2; i++) {
            if (str.charAt(i) != str.charAt(str.length() - i - 1)) {
                return false;
            } 
        }
        
        return true;
    }
}

END

相关文章
相关标签/搜索