LeetCode#7 Reverse Integer整数反转

本文详细解析LeetCode第7题——整数反转,涵盖题目描述、解题思路、源代码及提交结果。在反转过程中,需注意处理整数溢出的情况,确保结果在32位整数范围内。建议在编程时将可能溢出的变量声明为long类型。
摘要由CSDN通过智能技术生成

题目描述

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.

分析

1.题目要求反转之后的结果整数不能超过int的范围,若超范围直接输出0。用math中的pow函数在本地编译器上能通过,但在LeetCode官网上提示Math在该题目中未定义。那就简单粗暴给出int型的最大值和最小值,直接比较。
2.函数中的rs变量最开始定义成int型,在提交的时候显示执行过程中会溢出,改用long型。

源代码

import java.util.Scanner;

public class ReverseInteger {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		ReverseInteger ri = new ReverseInteger();
		System.out.println(ri.reverse(a));
		
	}
	
	int reverse(int x) {
		long rs = 0;
		int max = 0x7fffffff, min = 0x80000000;
//		int max = (int) Math.pow(2,31) - 1, min = -1 * (int)Math.pow(2, 31);
		if(x > max || x < min)
			return 0;
		for(int i = 0; x != 0; x = x/10) {
			rs = rs*10 + x%10;
			if(rs > max || rs < min)
				return 0;
		}
		return (int)rs;
	}
}

提交结果

在这里插入图片描述

总结

int型最大值:0x7fffffff
int型最小值:0x80000000
输入整数的范围是int型的取值范围时,尽量把运算中用到的变量定义为long型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值