# 引言
题目链接:https://leetcode.com/problems/reverse-integer/description/
# 题目大意
给出一个 32 位整型数字 ( int32
), 输出这个数字翻转后的数字。
- Example1
Input: 123
Output: 321
- Example2
Input: -123
Output: -321
- Example3
Input: 120
Output: 21
# 题解
# 一句话题解
水题,考虑正负,按照转换二进制的套路走一波就行
复杂度 O(n)
, 其实和数字的位数有关一个常数级别复杂度
# AC 代码
c++
版本
class Solution | |
{ | |
public: | |
int reverse(int x) | |
{ | |
int retSymbol = x < 0 ? -1 : 1; | |
long long retNum = 0; | |
x *= retSymbol; | |
while (x) | |
{ | |
retNum *= 10; | |
retNum += x % 10; | |
x /= 10; | |
} | |
if ((retNum * retSymbol > INT_MAX) || (retNum * retSymbol < INT_MIN)) | |
{ | |
retNum = 0; | |
} | |
return retNum * retSymbol; | |
} | |
}; |
go
版本
const INT_MAX = int(^uint32(0) >> 1) | |
func abs(x int) int { | |
if x < 0 { | |
return -x | |
} | |
return x | |
} | |
func reverse(x int) int { | |
res := 0 | |
for 0 != x { | |
if INT_MAX / 10 < abs(res) { | |
return 0 | |
} | |
res = res * 10 + x % 10 | |
x = x / 10 | |
} | |
return res | |
} |