您的位置:首页 > 编程语言 > Go语言

[LeetCode-Algorithms-9] "Palindrome Number" (2017.9.14-WEEK2)

2017-09-14 14:40 387 查看

题目链接:Palindrome Number

题目描述:

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.

(1)思路:这个题就是确定整数是否是回文,要注意Do this without extra space,使用int转换字符串可以判断是否回文但是需要新的空间,就违反了这个规定。不如直接把这个整数逆序然后和原整数比较是否相等。我觉得负数不是回文数。

(2)代码:

bool isPalindrome(int x) {
if(x < 0 || (x!=0 && x % 10 == 0)) return 0;
int temp = x;
int rev_x = 0;
while (temp > 0) {
rev_x = temp % 10 + rev_x * 10;
temp /= 10;
}
return rev_x == x;
}


(3)提交结果:

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