整数反转
版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~
- Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
- 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
欢迎来踩~~~~