7. Reverse Integer

来源:互联网 发布:知福茶叶怎么样 编辑:程序博客网 时间:2024/06/05 08:20

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

思路:反转数字,按位拆解,注意正负号及溢出的问题

class Solution {public:    int reverse(int x) {        long long res = 0;        while(x) {            res = res*10 + x%10;            x /= 10;        }        return (res<INT_MIN || res>INT_MAX) ? 0 : res;    }};
这里还要注意一下不同编程语言负数求余的问题。

C++:商向零取整

-23%10 = -3

Python:商向负无穷取整

-23%10 = 7

0 0