【LeetCode007算法/编程练习C++】数字逆序(atol)
来源:互联网 发布:印度入侵中国边界知乎 编辑:程序博客网 时间:2024/06/14 23:50
7. Reverse Integer
//溢出的话设为0- Total Accepted: 192898
- Total Submissions: 815127
- Difficulty: Easy
- Contributors: Admin
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
注意事项:
1.超过2147483647要设为0
2.string转long可以用atol,类似的转int用atoi
3.long要比long int快很多,用long int需要16ms但long只需要6ms
--------------------------------答案分割线-----------------------------
利用了string,转换起来方便了很多。
class Solution {public:int reverse(int x) {string s = to_string(x >= 0 ? x : -x);string temp="";for (int i = 0; i<s.size(); i++) {temp+= s[s.size() - 1 - i];}long pre_result = 0;pre_result = atol(temp.c_str());if (pre_result > 2147483648&&x<0 )return 0;else if (pre_result > 2147483647 && x >= 0)return 0;else return int((x>=0?1:-1)*pre_result);}};
运行结果如图,可以看出来速度还是可以的……
下面分享Top Solution里看到的非常优雅的非常简洁的方法://看着好简洁啊,竟然只有7行………………
class Solution {public: int reverse(int x) { long long res = 0; while(x) { res = res*10 + x%10; x /= 10; } return (res<INT_MIN || res>INT_MAX) ? 0 : res; }};再刷一题去次饭……
- 【LeetCode007算法/编程练习C++】数字逆序(atol)
- 【LeetCode008-009算法/编程练习C++】string转int(atoi),判断数字是否是回文
- 编程算法 - 链表逆序 代码(C)
- [C练习]字符串逆序
- C语言编程练习--念数字
- 【C】逆序排列数字
- 编程练习之句子逆序
- 编程算法 - 数组中的逆序对 代码(C)
- C#--逆序算法
- 数组逆序算法C
- C/C++预习:数字逆序输出(2,折半)
- (c++)输入10个数字,然后逆序输出。
- C语言atol用法
- 【编程练习】单链表逆序Java实现
- C语言小函数——atol(自己实现)
- C语言逆序输出某个数字
- C/C++编程小练习 数独(DFS算法实现)
- 算法导论第二章2-4 逆序对(c++)
- Android内存泄漏的避免方法
- RGB颜色查询对照表
- Ipad项目初涉UISplitViewController
- Andriod底层第三课---启动流程
- 手把手教你理解梯度下降法
- 【LeetCode007算法/编程练习C++】数字逆序(atol)
- 单点登录的原理和简单实现
- Hive SQL 和 MR 异常之 reduce拉取数据失败
- 简单的界面登录实现(struts+hibernate实现)
- ios 自定义相册开发
- Visual Studio常用快捷键
- ubuntu14安装maven
- Android官方下拉刷新控件SwipeRefreshLayout+ListView 介绍
- 蓝鸥iOS从零基础到精通就业-C语言入门 17指针二