您的位置:首页 > 其它

Leetcode:Palindrome Number

2015-07-04 11:21 281 查看
题目出处:https://leetcode.com/problems/palindrome-number/

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

翻译:判断一个整型数是否是回文数

思路:将整型数转化为字符串,依次比较首尾

代码:

<span style="background-color: rgb(204, 255, 255);">public class Solution {
    public boolean isPalindrome(int x) {
      boolean ispm = false;
		if(x<0)
			ispm = false;
		
		String s = x + "";
		int len = s.length();
		
		if(len % 2 == 0) {
			for(int i = 0; i<=(s.length()-1)/2; i++) {
				if(s.charAt(i) != s.charAt(len-1 - i))
				{
					ispm = false;
					break;

				} else 
					ispm = true;
			}
		} else {
			for(int i = 0; i<=s.length()/2; i++) {
				if(s.charAt(i) != s.charAt(len-1 - i)) {
					ispm = false;
					break;
				}
				else 
					ispm = true;

			}
		}
		
		return ispm;
    }
}</span>


另外,也看了下大牛的代码,真精炼!出处:http://blog.csdn.net/hcbbt/article/details/44001229

代码如下:

public class Solution {

    public boolean isPalindrome(int x) {
        long xx = x;
        long new_xx = 0;
        while (xx > 0) {
            new_xx = new_xx * 10 + xx % 10;
            xx /= 10;
        }
        return new_xx == x;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: