7. Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

 

 1 int reverse(int x) {
 2     long int res = 0;
 3     int y=x>0?x:-x;
 4     while(y != 0){
 5         res = res*10 + y%10;
 6         y = y/10;
 7     }
 8     res = x>0?res:-res;
 9     if(res > INT_MAX || res < INT_MIN)
10         return 0;
11     return res;
12 }

注意res要设为long int

取一个数的个位用%

去掉一个数的个位用/

INT_MAX

INT_MIN

 

 1 class Solution(object):
 2     def reverse(self, x):
 3         """
 4         :type x: int
 5         :rtype: int
 6         """
 7         s = str(x)
 8         if s[0] == '-':
 9             res = int('-' + s[1:][::-1])
10         else:
11             res = int(s[::-1])
12         if -2147483648 <= res <= 2147483647:
13             return res
14         else:
15             return 0

str()把任意表达转换为字符串

s[::-1]将字符串倒过来

 

转载于:https://www.cnblogs.com/fullest-life/p/6476174.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值