天天看點

Leetcode-7 Reverse Integer (java)

7. Reverse Integer

原題目

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321
           

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

翻譯

反轉一個整數資料

Example1: x = 123, return 321
Example2: x = -123, return -321
           

注意:在編碼之前有一些問題需要考慮,如果你已經考慮了這些問題,這将是你的加分點。

如果該整數的最後一位是0,那麼僵該輸出什麼呢?比如 10, 100

反轉後的整數也許會産生溢出,假定輸入的是一個32位的整數,如果反轉

1000000003

将産生溢出,那這種情況該如何處理呢?

如果發生了溢出,就直接傳回為0.

解決思路

需要考慮三個方面的問題。

  1. 需要考慮負數的反轉。
  2. 如果整數的末尾是0,比如10, 100, 那麼反轉後為1, 1
  3. 如果反轉後産生了溢出,那麼就直接傳回 0

解決思路為:

定義一個long 類型的變量result,來存儲反轉後的整數

然後循環反轉,注意負數的問題,同時檢測到發生了溢出,就傳回0

代碼示例-Java

package com.yumo.java.airthmetic.leetcode;

/**
 * Created by yumodev on 8/17/16.
 * 反正整形字元串
 */
public class ReverseInteger_7 {
    public static int reverse(int x) {
        long result = 0;
        while (x != 0){
            result = result * 10 + x % 10;
            x = x / 10;

            if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){
                result = 0;
                break;
            }
        }

        return (int)result;
    }

    public static void main(String[] args) {
        int x  = 1000000003;
        long startTime = System.nanoTime();
        int result = reverse(x);
        long endTime = System.nanoTime();
        long time = endTime - startTime;

        System.out.println("reverse:" + result + " time:" + time);
    }
}