Palindrome Number & Reverse Integer

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

分析:把一个数倒过来,然后看两个数是否相同。

 1 public class Solution {
 2     public boolean isPalindrome(int x) {
 3         if (x < 0) {
 4             return false;
 5         }
 6         long palindromeX = 0, inputX = x;
 7         while (x > 0) {
 8             palindromeX = palindromeX * 10 + (x % 10);
 9             x = x / 10;
10         }
11         return palindromeX == inputX;
12     }
13 }

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 1 public class Solution {
 2     public int reverse(int x) {
 3         boolean isPositive = true;
 4         
 5         if (x < 0) {
 6             x = -x;
 7             isPositive = false;
 8         }
 9         
10         long reversedValue = 0;
11         while (x != 0) {
12             reversedValue = reversedValue * 10 + x % 10;
13             x /= 10;
14         }
15         if (Math.abs(reversedValue) > Integer.MAX_VALUE) return 0; 
16         
17         return isPositive ?  (int)reversedValue : (int)(-reversedValue);
18     }
19 }
posted @ 2016-12-29 00:15  北叶青藤  阅读(225)  评论(0编辑  收藏  举报