欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

LeetCode - Easy - 7. Reverse Integer

程序员文章站 2022-06-28 10:08:35
TopicMathDescriptionhttps://leetcode.com/problems/reverse-integer/Given a 32-bit signed integer, reverse digits of an integer.Note:Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2³...

Topic

  • Math

Description

https://leetcode.com/problems/reverse-integer/

Given a 32-bit signed integer, reverse digits of an integer.

Note:

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

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Example 4:

Input: x = 0
Output: 0

Constraints:

  • -2³¹ <= x <= 2³¹ - 1

Analysis

经验教训:

判断溢出时的老路:

boolean sign = x < 0;
...
if(sign && result > 0 || !sign && result < 0) {
	return 0;
}

但是用在本题就不好用了。

System.out.println(Integer.MAX_VALUE + 1);// -2147483648
System.out.println(964632435 * 10);// 1056389758

964632435 * 10明明溢出了,却还是正数。猜测原因是964632435 * 10底层算法为10个964632435进行累加,验证代码如下:

int result = 0;
for (int i = 0; i < 10; i++)
	result += 964632435;
System.out.println(result);// 1056389758

猜测正确。

Submission

public class ReverseInteger {
	public int reverse(int x) {
		int result = 0, last = 0;
		while (x != 0) {
			last = result;
			result = result * 10 + x % 10;
			if (result / 10 != last) {
				return 0;
			}
			x /= 10;
		}
		return result;
	}

	public static void main(String[] args) {
		System.out.println(Integer.MAX_VALUE + 1);// -2147483648
		System.out.println(964632435 * 10);// 1056389758
		int result = 0;
		for (int i = 0; i < 10; i++)
			result += 964632435;
		System.out.println(result);// 1056389758
	}
}

Test

import static org.junit.Assert.*;
import org.junit.Test;

public class ReverseIntegerTest {

	@Test
	public void test() {
		ReverseInteger obj = new ReverseInteger();

		assertEquals(321, obj.reverse(123));
		assertEquals(-321, obj.reverse(-123));
		assertEquals(21, obj.reverse(120));
		assertEquals(0, obj.reverse(0));
		assertEquals(0, obj.reverse(1534236469));
	}
}

本文地址:https://blog.csdn.net/u011863024/article/details/112007198