博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Algorithm 07_Reverse Integer
阅读量:5136 次
发布时间:2019-06-13

本文共 1219 字,大约阅读时间需要 4 分钟。

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

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.

 
分析:本题理论上很简单,但对溢出的处理需要谨慎。这里本人用了unsigned long来保存reverse结果。
 
1 class Solution { 2 public: 3     int reverse(int x) { 4         bool isNegative = false; 5         if(x<0){ 6             x=-x; 7             isNegative = true; 8         } 9         unsigned long result = 0;10         while(x){11             result = result*10 + x%10;12             x = x/10;13         }14         if(result > INT_MAX) return 0;15         return (isNegative)? int(-result) : int(result) ;16         17     }18 };

 

转载于:https://www.cnblogs.com/chen0958/p/4356644.html

你可能感兴趣的文章
JS之BOM的window对象
查看>>
日期计算、正则、sequence、索引、表连接、mybatis
查看>>
12月7日站立会议
查看>>
Node.js_HTTP模块
查看>>
vscode+vue
查看>>
ros头文件引用
查看>>
【一】Swift 3.0 新浪微博项目实战 -整体框架搭建
查看>>
C语言函数库
查看>>
十四种Java开发工具点评
查看>>
2018年阿里巴巴关于java重要开源项目汇总
查看>>
VMware 安装 centos7
查看>>
HTML5 存储API介绍(收集)
查看>>
“引用的账户当前已锁定,切无法登录“问题解决方案
查看>>
关于上课了软件的认识
查看>>
Windows操作系统安全加固
查看>>
PhoneGap实践(Native Api调用 + 自定义Plugin(BarcodePlugin))
查看>>
Tomcat发布网站知识集锦
查看>>
数据库存入图片成功但显示不出来
查看>>
ManicTime软件破解版自用
查看>>
运输问题(网络流24)
查看>>