美文网首页
LeetCode算法题-Easy-Math(7、9)

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

作者: Dane_404 | 来源:发表于2019-02-13 08:50 被阅读0次

    两道题的解题思路一样,取模不断的拿个位数做累加,用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;
        }
    }
    

    相关文章

      网友评论

          本文标题:LeetCode算法题-Easy-Math(7、9)

          本文链接:https://www.haomeiwen.com/subject/qlbkeqtx.html