整数反转


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


  • Reverse digits of an integer.

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

click to show spoilers.

  • Have you thought about this?

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

  • 題目大意:把一个整数的数字顺序反转,正负号不变。

  • 思路:定义一个临时变量转存这个整数,如果是负数就变成它的相反数,然后进行循环,每次对10求余取出这个整数的最后一位,然后把这个数除以10。

  • 代码:

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);
 }
};
  • 然后这样的话是可以通过牛客网上的测试数据的,但是关键是它题目Have you thought about this?后边的要求,大意是要考虑int类型的溢出问题,这里有两种思路:

(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
欢迎来踩~~~~


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值