LeetCode算法题-Easy-Math(7、9)

2019-02-13  本文已影响0人  Dane_404

两道题的解题思路一样,取模不断的拿个位数做累加,用long型防止越界。

7. Reverse Integer

题目:Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21

class Solution {
    public int reverse(int x) {
     
       long res = 0;
       while (x != 0) {
          res = 10 * res + x % 10;
          x /= 10;
        }
      return (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) 
              ? 0 : (int) res;
    
    }
}

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.

class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        int temp = x;
        long res = 0;
        while(temp != 0){  
            res = res * 10 + temp % 10;
            temp /= 10;
        }
      
        if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE 
              || (int)res != x){
            return false;
        }
        
        return true;
    }
}
上一篇下一篇

猜你喜欢

热点阅读