[leetcode 7]

[Leetcode] 7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21

簡單來說就是反轉數值,不過正負不變。

c++的code

1
2
3
4
5
6
7
8
9
10
int reverse(int x) {
int y = 0;
while (x!=0)
{
if ( abs(y) > INT_MAX / 10)return 0;//防止溢位
y = y * 10 + x % 10;
x /= 10;
}
return y;
}

Runtime: 20 ms, faster than 25.65% of C++ online submissions for Reverse Integer.
雖然寫的簡單,但是跑得有點慢就是了。


Comments: