Seawolf 发表于 2019-8-28 06:27:45

leetcode 9. Palindrome Number

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;
    }
}
页: [1]
查看完整版本: leetcode 9. Palindrome Number