文章目录

正题

Reverse digits of an integer.

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

思考

改题为简单难度(水题),根据题意可以依次取到给定的整型数x的最高位到最低的数,然后依次将其乘10的x次幂后进行累加即可得到结果。这里,要知道32位的整型一共有九个0,故声明i=1000000000;

代码

[code lang=”cpp”]
class Solution {
public:
int reverse(int x) {
long int i = 1000000000, rev_i = 1, r = 0, start = 0;
while (x != 0) {
int c = x / i;
if (start == 0 && c != 0) start = 1;
if (start == 0 && c == 0) {
i /= 10;
continue;
}
r += x / i * rev_i;
if (i == 1) break;
x %= i;
rev_i *= 10;
i /= 10;
}
return (r > INT_MAX || r < INT_MIN) ? 0 : r;
}
};
[/code]


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

Share:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.