Given an integer x
, return true
if x
is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
- For example,
121
is a palindrome while123
is not.
class Polindrome {public boolean isPalindrome(int x) {int given =x;int reverse=0;while(given >0){reverse = 10*reverse +given%10;given = given/10;}if(reverse == x)return true;return false;}}
This one only goes through half the elements
class Palindrome {public boolean isPalindrome(int x) {
// negative numbers are not a palindrome
//any number with zero in units. but not Zero by itself
if(x<0 || (x % 10 == 0 && x != 0) )return false;int numDigits = String.valueOf(x).length();int half = numDigits/2;int rev=0;int given = x;for(int i=0;i<half;i++){rev = 10*rev+given%10;given=given/10;}if(numDigits%2 != 0)given = given/10;if(rev==given)return true;return false;}}
No comments:
Post a Comment