美文网首页
7. Reverse Integer

7. Reverse Integer

作者: 要上班的斌哥 | 来源:发表于2017-09-01 23:19 被阅读18次

题目

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?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

NOTE:The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

解题思路:
这个题目是让我们反转一个整数,需要我们留意溢出的问题

  1. 从各位开始分别取出 个位 十位 百位... 上的数值,比如 123 ,个位就是 3, 十位数字是 2,那就是20,百位数字是1,那就是100。反转过来就是 3100 + 210 + 1 = 321
  2. 最后需要判断一下反转后的数字是否在 32 位 int 表示范围内溢出

解题代码:

class Solution {
public:
    int reverse(int x) {
// int 类型的 x 反转后可能会产生溢出,所以我们使用 long long 类型来存放反转后的数字
    long long num = 0;
// 对于 c/c++ 来说 0 是 false,其他非 0 都是 true
    while (x) {
        num = num * 10 + x%10;
        x = x / 10;
    }
// 判断是否产生溢出
    if (num > INT_MAX || num < INT_MIN) {
        num = 0;
    }
    
    return num;
    }
};

参考

https://leetcode.com/problems/reverse-integer/description/

相关文章

网友评论

      本文标题:7. Reverse Integer

      本文链接:https://www.haomeiwen.com/subject/fpcljxtx.html