美文网首页
7. Reverse Integer

7. Reverse Integer

作者: 捂不暖的石头 | 来源:发表于2017-10-31 17:54 被阅读0次

    Reverse digits of an integer.
    Example1: x = 123, return 321
    Example2: x = -123, return -321

    Note:
    The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

    Python

    class Solution(object):
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            result = 0
            if x < 0:
                result = int('-' + str(x)[1:][::-1])
            else:
                result = int(str(x)[::-1])
            if result >= 2**31 - 1 or result <= - 2**31:
                return 0
            else:
                return result
            
    

    Java

    class Solution {
        public int reverse(int x) {
            String x_str = String.valueOf(x);
            char[] result_chars = x_str.toCharArray();
            char[] x_chars = x_str.toCharArray();
            if (x_chars[0] == '-'){
                for(int i = 1; i < x_str.length(); i ++){
                    result_chars[i] = x_chars[x_str.length() - i];
                }
            }else{
                for(int i = 0; i < x_str.length(); i ++){
                    result_chars[i] = x_chars[x_str.length() - i - 1];
                }
            }
            int result_int = 0;
            try {
                result_int = Integer.parseInt(String.valueOf(result_chars));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            return result_int;   
        }
    }
    

    参考答案

    Python

    class Solution:
        # @param {int} n the integer to be reversed
        # @return {int} the reversed integer
        def reverseInteger(self, n):
            if n == 0:
                return 0
                
            neg = 1
            if n < 0:
                neg, n = -1, -n
            
            reverse = 0
            while n > 0:
                reverse = reverse * 10 + n % 10
                n = n / 10
            
            reverse = reverse * neg
            if reverse < -(1 << 31) or reverse > (1 << 31) - 1:
                return 0
            return reverse
    

    Java

    public class Solution {
        /**
         * @param n the integer to be reversed
         * @return the reversed integer
         */
        public int reverseInteger(int n) {
            int reversed_n = 0;
            
            while (n != 0) {
                int temp = reversed_n * 10 + n % 10;
                n = n / 10;
                if (temp / 10 != reversed_n) {
                    reversed_n = 0;
                    break;
                }
                reversed_n = temp;
            }
            return reversed_n;
        }
    }
    

    相关文章

      网友评论

          本文标题:7. Reverse Integer

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