Reverse Integer--整数的反转
原题:
Reverse digits of an integer.
=>反转一个整数的数字。例子如下:
Example1: x = 123, return 321
Example2: x = -123, return -321
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.
=>假如最后一位是0,那么结果会是什么样的呢?比如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?
=>你有考虑过反转后的溢出问题嘛?假如是32bit的整数,1000000003反转后就会溢出。你怎么处理这样的情况?
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).
=>抛出一个异常?很好,假如不能抛出异常呢?其实可以重新定义这个函数(比如加一个参数)
class Solution {
public:
int reverse(int x) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case. };
晓东分析:
这个题目就反转本身而言是很简单的,晓东就不多分析了。所以,我主要来说一下溢出的问题,我个人的思路就是在得到反转的值的时候,先不乘上最高位,留着进行比较。
所以总的来说,还是不复杂的。
代码实现:
class Solution {
public:
int reverse(int x) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int max_first_bit = 2; //default for 4
int max_remain_num = 147483647; int num = 0;
int temp = abs(x); while(temp >= 10){
num = num * 10 + temp % 10;
temp /= 10;
} switch(sizeof(int)){
case 1:
max_first_bit = 1;
max_remain_num = 27;
break;
case 2:
max_first_bit = 3;
max_remain_num = 2767;
break;
case 4:
max_first_bit = 2;
max_remain_num = 147483647;
break;
case 8:
max_first_bit = 9;
max_remain_num = 223372036854775807;
break;
} if(x > 0){
if (temp < max_first_bit)
return num * 10 + temp % 10;
else if(num <= max_remain_num)
return num * 10 + temp % 10;
else
throw x;
}else{
if (temp < max_first_bit)
return 0 - (num * 10 + temp % 10);
else if(num <= max_remain_num + 1)
return 0 - (num * 10 + temp % 10);
else
throw x;
} }
};
执行结果:
1020 / 1020 test cases passed.
|
Status:
Accepted |
Runtime:
28 ms |
希望大家有更好的算法能够提出来,不甚感谢。
若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·
最新文章
- 使用 MimeKit 和 MailKit 发送邮件
- 2016 - 2 - 20 ARC知识总结(二 autorelease概念及实现)
- python类型转换、数值操作(转)
- SSH调试
- IE6中的常见BUG与相应的解决办法
- Swift的基础,操作符,字符串和集合类型
- crawler_网络爬虫中编码的正确处理与乱码的解决策略
- MVC验证12-使用DataAnnotationsExtensions对整型、邮件、最小值、文件类型、Url地址等验证
- oracle使用中的一些问题
- 用css画一个哆啦A梦
- Mac PD 虚拟机 鼠标双击 输入 ";c"; 解决
- Django ModelForm 校验数据格式
- three.js - 动画 图形统计帧频 dat.GUI
- php功底你修炼到哪一级
- 使用 StoryBoard 实现左右按钮切换图片的浏览效果
- SQL之联合查询学习笔记
- Oracle快速克隆安装
- php 数字格式化
- C语言简易三子棋
- 【java】中缀表达式转后缀表达式 java实现
热门文章
- video.js分段自动加载视频【html5视频播放器】
- Robot Framework Selenium(RFS :web自动化测试神器)
- spring_150906_sqlmapclientdaosupport_getSqlMapClientTemplate
- oracle语句练习
- 使用fastadmin系统自带的图片上传plupload
- seat
- 备份Kylin的Metadata
- HashMap实现原理及常见问题
- 虚拟环境中pip install requirments.txt: Cannot fetch index base URL https://pypi.python.org/simple/
- Spring JDBC主从数据库访问配置