您的位置:首页 > 其它

LeetCode-- Palindrome Number

2015-12-02 10:29 274 查看
题目描述:

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.

本题就是判断一个整数是否为回文。
特殊要求是不能转化为string,其实这个限制我认为不是很有意义,因为现实应用中很少会有要求。

思路:
1. 一次遍历,不断/10,得到x的位数 : digits
2. 遍历digits[0, len/2], 使用n1,n2分别表示x从右边“拿掉”1位和x从左“拿掉”一位之后的数,拿掉的数分别为x1,x2
x1 = n1%10;
n1/=10;
x2 = n2 / Math.Pow(len(digits - i))
n2 -= x2 * Math.Pow(len(digits - i)),其中i∈[0, len/2]

实现代码:

public class Solution {
public bool IsPalindrome(int x) {
if(x < 0){
return false;
}

if(x == 1){
return true;
}

// first loop , to know how many digit
var digits = 0;
var n = x;
while(n != 0){
n/=10;
digits++;
}

int n1 = x; // digits from left to right
int n2 = x; // digits from right to left
for(var i = 1;i <= digits/2; i++){
var p = Math.Pow(10, digits-i);
int x1 = n1 % 10;
int x2 = (int) (n2 / p);

if(x1 != x2){
return false;
}

n1 /= 10;
n2 -= (int)(x2 * p);
}

return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: