题目描述
题目链接:7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
例子
例子 1
Input: 123
Output: 321
例子 2
Input: -123
Output: -321
例子 3
Input: 120
Output: 21
Note
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解题思路
题目比较简单,只需要不断求余数即可,注意由于正负数转化的问题我们需要先将 x
转为长整形避免溢出,对结果变量也是一样。代码如下:
1 |
|
- 时间复杂度: O(digits of
x
) - 空间复杂度: O(1)
GitHub 代码同步地址: 7.ReverseInteger.cpp
其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions