用python给定一个整数,请将该数各个位上数字反转得到一个新数。新数也应满足整数的常见形式,即除非给定的原数是0,否则反转后得到的新数的最高位数字不应该是零
时间: 2024-05-11 07:18:21 浏览: 20
可以先将整数转换成字符串,然后反转字符串,最后再将反转后的字符串转换回整数。需要注意的是,需要判断反转后的数的最高位是否为零。
代码如下:
```python
def reverse_integer(num):
if num == 0:
return 0
s = str(num)
s_reverse = s[::-1]
new_num = int(s_reverse)
# 判断最高位是否为零
if new_num != 0 and new_num // 10**(len(s)-1) == 0:
return 0
return new_num
```
测试一下:
```python
print(reverse_integer(123)) # 输出 321
print(reverse_integer(120)) # 输出 21
print(reverse_integer(0)) # 输出 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
```
用python写一个给定一个整数,将该数各个位上数字反转得到一个新数新数不得有多余的前导零
以下是Python代码:
```python
def reverse_integer(num):
if num == 0:
return 0
# 判断正负号
sign = 1
if num < 0:
sign = -1
num = -num
# 反转数字
reverse_num = 0
while num > 0:
reverse_num = reverse_num * 10 + num % 10
num //= 10
# 加上正负号
reverse_num *= sign
return reverse_num
```
代码说明:
1. 首先判断输入的整数是否为0,如果是直接返回0。
2. 判断整数的正负号,并将负数转为正数处理。
3. 反转数字,使用while循环,每次取出最后一位数字,并将其加到反转后的数字上。
4. 最后再加上正负号,返回反转后的数字。
测试代码:
```python
print(reverse_integer(123)) # 321
print(reverse_integer(-123)) # -321
print(reverse_integer(120)) # 21
print(reverse_integer(0)) # 0
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)