[Leetcode]解题文档- Reverse Integer
2016-05-07 19:55
489 查看
题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
题目意思很简单,但是需要考虑溢出。
尝试了字符串的解法和纯int数字解,发现后者效率更高,那么笔者是如何判断是否溢出的呢?比如1234567899,正序不溢出,逆序溢出。
做法:先判断位数,位数等于10的话,将逆序得到的结果再逆序,与原先的x进行比较,若不等,则溢出。效率还算比较高的一种判断方法。
解法1:
解法二:
该方法耗时12ms..比前一个慢了些许。
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
题目意思很简单,但是需要考虑溢出。
尝试了字符串的解法和纯int数字解,发现后者效率更高,那么笔者是如何判断是否溢出的呢?比如1234567899,正序不溢出,逆序溢出。
做法:先判断位数,位数等于10的话,将逆序得到的结果再逆序,与原先的x进行比较,若不等,则溢出。效率还算比较高的一种判断方法。
解法1:
class Solution { public: int reverse(int x) { if(x==0) return 0; int res=x%10; int Backup_x=x; x=x/10; int flag=1;//记录位数 while(x!=0) { res=x%10+res*10; x=x/10; flag++; } //check overflow if(flag==10&&Check_Reverse(res)!=Backup_x) { return 0; } return res; } private: int Check_Reverse(int x){ int res=x%10; x=x/10; while(x!=0) { res=x%10+res*10; x=x/10; } return res; } };
解法二:
class Solution { public: int reverse(int x) { if(x==0||abs(x)<0) return 0; int flag=x>0?1:-1; x=abs(x); // cout<<"x"<<x<<endl; stringstream ss; string str; ss<<x; ss>>str; string newstr=""; for(int i=0;i<str.size();i++) { newstr=str[i]+newstr; } x = atoi(newstr.c_str()); //check overflow // cout<<check_reverse(x)<<" "<<newstr<<endl; if(newstr.size()==10&&check_reverse(x)!=newstr) { return 0; } return flag*x; } private: string check_reverse(int x){ stringstream ss; string str; ss<<x; ss>>str; return str; } };
该方法耗时12ms..比前一个慢了些许。
相关文章推荐
- 二进制枚举法枚举子集
- HDU2444 二分图判断(BFS 的染色法) + 求最大匹配边数(DFS 的匈牙利算法)
- 下一阶段学习安排
- jenkins手动安装插件
- python的一些函数
- OpenCV(学习笔记3)-图像腐蚀
- PopupWindow进阶
- Python/Pelican搭建自己个人博客
- 解决MindManager在win8/10下不能运行的问题
- centos6.7 搭建 redis集群
- HDU 4167 User Names (字符串水题)
- 电源设计注意事项
- mac 显示隐藏文件
- 数的16进制转换加选择排序法,冒泡排序法
- 网页制作的九大要点
- 蛇形填数
- 理解MySQL——架构与概念
- JSON与fastjson
- 手机触屏事件(touch事件,网上资料有限,想具体了解还需要自己研究)
- 常用排序算法之快速排序