(Java)leetcode-7 Reverse Integer

topic

[Integer] Flip
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

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Thinking

To flip this question is not difficult to figure, how difficulty is to determine integer overflow has occurred.
Before we die 10 and applied to the new x value is determined to overflow, if the overflow occurs, the new values in the reverse operation has not equivalent to the original value, thereby determining overflow occurred.

Code

class Solution {
	public int reverse(int x)
	{
	    int result = 0;

	    while (x != 0)
	    {
	        int tail = x % 10;//个位数字
	        int newResult = result * 10 + tail;
	        if ((newResult - tail) / 10 != result) //判断是否溢出
	        { return 0; }
	        result = newResult;
	        x = x / 10;
	    }

	    return result;
	}
}

Present the results

Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Integer.
Memory Usage: 32.4 MB, less than 100.00% of Java online submissions for Reverse Integer.

Published 143 original articles · won praise 45 · views 70000 +

Guess you like

Origin blog.csdn.net/z714405489/article/details/89576859