给定一个整数(可以为负),将该数各个位上的数字反转得到一个新数,新数不得有多余的前导0。
时间: 2024-05-29 13:11:38 浏览: 4
算法思路:
- 将整数转为字符串,然后将字符串反转;
- 如果字符串中有负号,将负号移动到字符串最前面;
- 去除字符串前面的0;
- 将得到的字符串转为整数,如果原来的数为负数,则结果也为负数。
算法实现(Python代码):
def reverse_num(num):
# 将整数转为字符串,然后将字符串反转
str_num = str(num)[::-1]
# 如果字符串中有负号,将负号移动到字符串最前面
if '-' in str_num:
str_num = '-' + str_num.replace('-', '')
# 去除字符串前面的0
str_num = str_num.lstrip('0')
# 将得到的字符串转为整数,如果原来的数为负数,则结果也为负数
return int(str_num) if num >= 0 else -int(str_num)
# 测试
print(reverse_num(123)) # 321
print(reverse_num(-123)) # -321
print(reverse_num(120)) # 21
print(reverse_num(-120)) # -21
print(reverse_num(0)) # 0
相关问题
给定一个整数可以为负将该数各个位上的数字反转得到一个新的数字,新数不得有多余的前导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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)