LeetCode 007 Reverse Integer

题目描述:Reverse Integer

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.

Example Questions Candidate Might Ask:

Q: What about negative integers?

A: For input x = –123, you should return –321.

Q: What if the integer’s last digit is 0? For example, x = 10, 100, …

A: Ignore the leading 0 digits of the reversed integer. 10 and 100 are both reversed as 1.

Q: What if the reversed integer overflows? For example, input x = 1000000003.

A: In this case, your function should return 0.

代码如下:

1class Solution { 2public: 3 int reverse(int x) { 4 5 int ret = 0; 6 7 while(x != 0){ 8 // handle overfolow or underflow 9 if(abs(ret) > 214748364){ 10 return 0; 11 } 12 ret = ret * 10 + x % 10; 13 x /= 10; 14 } 15 return ret; 16 17 } 18};

 Java:

1public int reverse(int x) { 2 3 int ret = 0; 4 5 while (x != 0) { 6 7 // 防止溢出,只要大于MAX/10就算溢出! 8 if (Math.abs(ret) > Integer.MAX_VALUE / 10) { 9 return 0; 10 } 11 ret = ret * 10 + x % 10; 12 x /= 10; 13 } 14 15 return ret; 16 }

本文同步分享在 博客“Yano_nankai”(CNBlog)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

java将前端的json数组字符串转换为列表

记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang

Android So动态加载 优雅实现与原理分析

背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我