Palindrome Number(lintcode 491)
Description
Check a positive number is a palindrome or not.
A palindrome number is that if you reverse the whole number you will get exactly the same number.
Notice:
It's guaranteed the input number is a 32-bit integer, but after reversion, the number may exceed the 32-bit integer.
Example
11, 121, 1, 12321 are palindrome numbers.
23, 32, 1232 are not palindrome numbers.
Interface
public class Solution {
/**
* @param num a positive number
* @return true if it's a palindrome or false
*/
public boolean palindromeNumber(int num) {
// Write your code here
}
}
Idea
Two ways. Treat num as a number or treat num as a string.
Solution
public class Solution {
/**
* @param num a positive number
* @return true if it's a palindrome or false
*/
public boolean palindromeNumber(int num) {
// treat num as a string
String str = Integer.toString(num);
int i = 0;
while (i < str.length() / 2) {
if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {
break;
}
++i;
}
return i == str.length() / 2;
}
}
public class Solution {
/**
* @param num a positive number
* @return true if it's a palindrome or false
*/
public boolean palindromeNumber(int num) {
// treat num as a number
int temp = num;
int rev = 0;
while (temp != 0) {
rev = rev * 10 + temp % 10;
temp = temp / 10;
}
return rev == num;
}
}