Reverse Integer

来源:互联网 发布:游戏常用算法 编辑:程序博客网 时间:2024/05/16 15:07

每日算法——letcode系列


问题 Reverse Integer

Difficulty: Easy

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.

class Solution {public:    int reverse(int x) {    }};

翻译

整数反转

难度系数:简单

将一个整数的数字反转

例如: x = 123, return 321
例如: x = -123, return -321

这些你考虑到了吗?

在进行编码前你应当问下面几个问题, 如果这些问题你都考虑到了,那面试的时候可能增加你的工资。

整数的最后一位为0的时候输出应该是什么? 比如整数为10、100等的时候。

是否注意到反转有可能越界? 假定输入的一个32位整数,反转1000000003会越界, 怎么来处理这种情况?

针对这个问题,当反转后有越界的情况返回0。

思路

此题的下面几个问题很不错。

代码

class Solution {public:    int reverse(int x) {        int digit = 0;        int carry = 0;        while (x != 0) {            carry = x % 10;            if (digit > INT32_MAX / 10 || digit < INT32_MIN / 10){                return 0;            }            digit = digit * 10 + carry;            x /= 10;        }        return digit;    }};
0 0