博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LeetCode】7. Reverse Integer
阅读量:6908 次
发布时间:2019-06-27

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

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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

 

(1)首先将x提升为64位num,若不然-INT_MIN将会溢出.

(2)将num取模10得到的每一位数字加入到返回值中,然后返回值乘10移位,得到数值上的结果ret

(3)判断ret是否超过int的范围,若超过,则返回0

时间复杂度为:O(k), k为x的位数

class Solution {public:    int reverse(int x) {        long long ret = 0;        int sign = (x<0)?-1:1;        x = abs(x);        while(x)        {            int digit = x % 10;            x /= 10;            ret = ret * 10 + digit;        }        ret *= sign;        if(ret > INT_MAX || ret < INT_MIN)            return 0;        else            return ret;    }};

转载地址:http://vrrdl.baihongyu.com/

你可能感兴趣的文章
一个URL链接到一个页面发生了什么?
查看>>
按位异或运算,交换两个变量中的数值
查看>>
Android--向SD卡读写数据
查看>>
J2EE的体系架构——J2EE
查看>>
安卓常用 widget
查看>>
大二暑假第一周进度报告
查看>>
ZROI2018提高day2t1
查看>>
EZOJ #87
查看>>
C++智能指针应用方式体验
查看>>
作业三:读《构建之法》1-5章读后感
查看>>
Hadoop综合大作业
查看>>
C#使用StreamWriter类写入文件文件
查看>>
响应式开发
查看>>
【LeetCode每天一题】Candy(分糖果)
查看>>
聊聊HTTPS和SSL/TLS协议
查看>>
日期与毫秒互转(转)
查看>>
python jinja 模板教程
查看>>
Stani's Python Editor下载
查看>>
使用apidoc 生成Restful web Api文档
查看>>
Linux 下后台运行程序,查看和关闭后台运行程序
查看>>