leetcode7.ReverseInteger(整数反转)

tech2024-04-11  8

题目:Reverse Integer 描述: 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. 来源:力扣(LeetCode)

分析: 1.给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31, 2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。 题目本身并不困难,重点在于如何判断边界问题。 2.什么是反转整数,示例已经很清楚, 就是给定你一个整数,将它倒序输出,当然,不能忽略了负数的情况。 3.反转整数的方法,可以考虑先转换为字符串,再进行处理,当然也增加了一些步骤。另一种办法,就是利用编程语言的特性,取余%,作除/的结合操作。比如要反转整数123,反转结果为321,很明显,首先得拿到他的个位数字,依次是十位,百位…。 如何取得其各位数值?取余可以做到。以123为例: 第一次:123 %10 = 3; 第二次:12 %10 = 2; 第三次:1 % 10 = 1;

题解一:这题简单,所以借机复习一下其他语言基础知识。 java版本:

/** * 方法一: * @param x * @return 返回结果 */ public static int reverse(int x){ long n=0; while (x!=0){ n = n*10+x%10; x = x/10; } return (int)n==n?(int)n:0; }

python版本:

def reverse(self, x: int) -> int: #整数转换成字符串 s=str(abs(x)) #字符串翻转 s=s[::-1] #若输入为负数,增加负号 if x <0: s ='-' + s #转换为整数 result = int(s) #边界判断 if result>=-2**31 and result<=2**31-1: return result else: return 0

c++版本:

#include <iostream> #include <algorithm> using namespace std; //整数反转: int reverse(int x) { long result = 0; while(x!=0){ result = result*10+x%10; x = x/10; } if(result>INT_MAX||result<INT_MIN){ return 0; }else{ return result; } }

c版本:

#include <stdio.h> #include <stdlib.h> int reverse(int x){ long res = 0; while (x!=0){ res = res*10+x%10; x/=10; } return res>2147483647 || res<-2147483648?0:res; }

解法二:这是一个关于边界的思考:先参考一下。 java中int的取值范围: 2147483647 -2147483648 我们可以对最后一位数字进行判断,如果当取值为214748364时,如果末位数字>-8或者<7明显肯定越界溢出。 Java代码:

/** * 方法二: * @param x * @return 返回结果res * 注意:int范围 -2^32~2^31(-2147483648 ~ 2147483647) */ public static int reverse1(int x){ final int MAX = 214748364;//最大上限, final int MIN = -214748364;//最小上限 int res = 0; while (x!=0){ //取到最后一位数字 int tmp = x % 10; //判断是否溢出上限(32位整数) if (res>MAX ||(res == MAX && tmp>7)){ //注意:2^31 = 2147483647 return 0; } //判断是否溢出下限(32位整数) if (res<MIN || (res == MIN && tmp<-8)){ return 0; } //满足条件,将数据反转 res = res*10+tmp; x/=10; } return res; }

tips:这个算法并非完全原创,借鉴了leetcode大佬王尼玛同学的部分思路。 end--------------------------------------------------------------------------------------------

最新回复(0)