1. 程式人生 > >LeetCode Reverse Integer

LeetCode Reverse Integer

Problem

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.

即返回一個數的逆序數。

Java 實現


/**
 * Reverse digits of an integer.
 * <p>
 * Example1: x = 123, return 321
 * Example2: x = -123, return -321
 *
 * @author li.hzh
 * @date 2017-10-11 22:07
 */
public class ReverseInteger { public static void main(String[] args) { int x = 123; int y = -321; int z = 1000000003; ReverseInteger instance = new ReverseInteger(); System.out.println(instance.reverse(x)); System.out.println(instance.reverse(y)); System
.out.println(instance.reverse(z)); } public int reverse(int x) { int result = 0; int tempResult = 0; while (x != 0) { int remainder = x % 10; result = result * 10 + remainder; if ((result - remainder) / 10 != tempResult) { return
0; } tempResult = result; x = x / 10; } return result; } }

分析

reverse中為具體實現,上面是簡單的測試用例。通過一次除以10 取餘來依次從後至前得到末尾數,構造逆序數。通過

if ((result - remainder) / 10 != tempResult) {
                return 0;
				}

逆計算來判斷整數是否溢位。