给定一个整数(可以为负),将该数各个位上的数字反转得到一个新数,新数不得有多余的前导0
时间: 2024-06-06 07:07:54 浏览: 14
。例如:
输入:123
输出:321
输入:-123
输出:-321
输入:120
输出:21
思路:将整数转为字符串,然后反转字符串,再转回整数即可。注意处理负数和前导零的情况。
Python代码:
class Solution:
def reverse(self, x: int) -> int:
if x < 0:
s = str(-x)
s = '-' + s[::-1]
else:
s = str(x)[::-1]
s = s.lstrip('0')
if s == '' or s == '-':
return 0
else:
return int(s)
相关问题
给定一个整数可以为负将该数各个位上的数字反转得到一个新的数字,新数不得有多余的前导0
算法思路:
1. 将给定整数转换为字符串;
2. 对于正数,直接反转字符串并转换为整数;
3. 对于负数,先将负号去掉,再反转字符串,最后将结果加上负号。
时间复杂度:O(n),其中 n 为数字的位数。
Python 代码实现:
```python
def reverse_integer(x):
if x == 0:
return 0
elif x > 0:
s = str(x)
y = int(s[::-1])
else:
s = str(-x)
y = -int(s[::-1])
return y if y.bit_length() < 32 else 0
```
C++ 代码实现:
```cpp
#include <iostream>
using namespace std;
int reverse_integer(int x) {
if (x == 0) {
return 0;
} else if (x > 0) {
string s = to_string(x);
reverse(s.begin(), s.end());
long long y = stoll(s);
return y > INT_MAX ? 0 : y;
} else {
string s = to_string(-x);
reverse(s.begin(), s.end());
long long y = -stoll(s);
return y < INT_MIN ? 0 : y;
}
}
int main() {
int x = -123;
int y = reverse_integer(x);
cout << y << endl; // 输出 -321
return 0;
}
```
给定一个整数(可以为负),将该数各个位上的数字反转得到一个新数python
可以使用字符串反转的方法来实现:
```python
def reverse_num(num):
s = str(num)
if s[0] == '-':
return int('-' + s[:0:-1])
else:
return int(s[::-1])
```
解释:
1. 将整数转化为字符串 `s`。
2. 如果该数字为负数,将其符号保留,然后反转其绝对值的字符串形式,再加上符号。
3. 如果该数字为正数,直接反转其字符串形式。
4. 将反转后的字符串转化为整数并返回。
测试:
```python
print(reverse_num(123)) # 321
print(reverse_num(-123)) # -321
print(reverse_num(0)) # 0
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)