|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
- Example 1:
- Input: 121
- Output: true
- Example 2:
- Input: -121
- Output: false
- Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
- Example 3:
- Input: 10
- Output: false
- Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
- Follow up:
- Coud you solve it without converting the integer to a string?
复制代码
First try, convert integer to string.
- class Solution {
- public boolean isPalindrome(int x) {
-
- String a = String.valueOf(x);
-
- return a.equals(reverse(a));
-
- }
-
- public String reverse(String str){
-
- int len = str.length();
-
- String re = "";
-
- for(int i = 0; i< len; i++){
-
- re = str.substring(i,i+1) + re;
-
- }
-
- return re;
- }
- }
复制代码
Second try without converting the integer to string.
- class Solution {
- public boolean isPalindrome(int x) {
-
- if(x < 0){
-
- return false;
- }
-
-
- return x == reverse(x);
-
- }
-
- public Integer reverse(int x){
-
- int result = 0;
-
- while(x != 0){
-
- result = result * 10 + x % 10;
-
- x = x/10;
- }
-
- return result;
- }
- }
复制代码 |
|