[Leetcode] reverse integer 反转整数
Posted 王大咩的图书馆
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] reverse integer 反转整数相关的知识,希望对你有一定的参考价值。
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer‘s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
题意:将一个整数反转。
思路:这题有几个要注意的地方:一、正负号;二、反转后的结果是否溢出。第二点很重要,关于这点题目中有详细的说明。这里有两种解法方法:
方法一:改变返回结果的变量类型为long long ,这样,若是最终计算的结果超过INT_MAX,就返回0;否则,结构符号输出即可。
代码如下:
1 class Solution { 2 public: 3 int reverse(int x) 4 { 5 long long res=0; 6 int cur=abs(x); 7 8 while(cur>0) 9 { 10 res=res*10+cur%10; 11 cur/=10; 12 } 13 if(res>INT_MAX) return 0; 14 return x>=0?res:-res; 15 } 16 };
方法二:不用改变返回的变量类型,在while循环中,在计算res之前,若res>INT_MAX/10,就返回0,因为若是大于,则后续的计算中乘以10 了,还是会大于,所以提前返回。代码如下:
1 class Solution { 2 public: 3 int reverse(int x) 4 { 5 int res=0; 6 int cur=abs(x); 7 8 while(cur>0) 9 { 10 if(res>INT_MAX/10) return 0; 11 res=res*10+cur%10; 12 cur/=10; 13 } 14 15 return x>=0?res:-res; 16 } 17 };
在LeetCode上测试时,第二种方法,明显好些。
以上是关于[Leetcode] reverse integer 反转整数的主要内容,如果未能解决你的问题,请参考以下文章
7. 反转整数 [leetcode 7: Reverse Integer]
7. 反转整数 [leetcode 7: Reverse Integer]