程序员

整数反转

2018-11-26  本文已影响0人  静水流深ylyang

版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

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).

class Solution {
public:
 int reverse(int x) {
 int temp = x > 0 ? x : (-x);
 int result = 0;
 while(temp)
 {
 result = result * 10 + temp % 10;
 temp /= 10;
 }
 return x > 0 ? result : (-result);
 }
};

(1)定义为返回的变量为long或者long long类型,判断如果大于int max32 = 0x7fffffff;或者小于int min32 = 0x80000000;就是溢出了。

(2)每次计算新的结果时,再用逆运算(把结果除以10)判断与上一次循环的结果是否相同,不同就溢出。

第二种思路很巧妙,我喜欢第二种思路。

class Solution {
public:
 int reverse(int x) {
 int temp = x > 0 ? x : (-x);
 int result = 0;
 while(temp)
 {
 int newResult = result * 10 + temp % 10;
 // 把newResult/10也就是把加上的temp%10又除掉了,如果不等于result,说明发生了溢出
 if((newRessult / 10) != result) return 0;
 result = newRessult;
 temp /= 10;
 }
 return x > 0 ? result : (-result);
 }
};

版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


上一篇下一篇

猜你喜欢

热点阅读