Reverse Integer
2015-06-18 17:36
453 查看
题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
代码:
class Solution:
# @param {integer} x
# @return {integer}
def reverse(self, x):
newString='';
inte = abs(x);
if inte > math.pow(2,31):
return 0
newStr=str(inte);
for s in newStr:
newString=s+newString;
if int(newString) > math.pow(2,31):
return 0
if x>=0:
return int(newString)
else:
return int('-'+newString)
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
代码:
class Solution:
# @param {integer} x
# @return {integer}
def reverse(self, x):
newString='';
inte = abs(x);
if inte > math.pow(2,31):
return 0
newStr=str(inte);
for s in newStr:
newString=s+newString;
if int(newString) > math.pow(2,31):
return 0
if x>=0:
return int(newString)
else:
return int('-'+newString)
相关文章推荐
- JavaScript面向对象
- eclipse 离线安装ADT
- Linux下安装启动多个Mysql
- 线程池实例
- RMAN 常用操作命令二(备份保留策略)
- 数据结构与算法-----双向线性链表
- RMAN 常用操作命令一
- MFC控件:listctrl使用方法总结
- HTML5 中websocket长连接的具体实现方法
- 9 Palindrome Number(判断是否为回文数Easy)
- 团队项目第二次冲刺(5)
- 第二阶段冲刺报告(六)
- js 创建hashmap
- 【弱省胡策】Round #5 Construct 解题报告
- MongoDB安装及复制集搭建
- Log4j打印JdbcTemplate及参数
- JVM 、JDK(c/c++)源代码下载
- 函数对象
- 怎样在Windows系统中获取开源软件SVN更多的Revision记录
- 容器set和multiset