7. Reverse Integer
被类型问题折磨的死去活来。。。。
public class Solution {
public int reverse(int x) {
long res = 0;
while (x != 0) {
res = res * 10 + x % 10;
x = x / 10;
if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) {
return 0;
}
}
return (int) res;
}
}9. Palindrome Number
我用string做的,还有一种方法是将int倒转一下,在比较是否相同。
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
if (x < 10) {
return true;
}
String s = "" + x;
int lo = 0;
int hi = s.length() - 1;
while (lo < hi) {
if (s.charAt(lo) != s.charAt(hi)) {
return false;
}
lo++;
hi--;
}
return true;
}
}
本文提供了两种算法实现:一种是反转整数的方法,该方法考虑了整数溢出的问题;另一种是判断一个整数是否为回文数的方法,通过字符串处理来进行判断。
713

被折叠的 条评论
为什么被折叠?



