【LeetCode007算法/编程练习C++】数字逆序(atol)
2016-12-23 10:53
411 查看
7. Reverse Integer
//溢出的话设为0Total 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; } };再刷一题去次饭……
相关文章推荐
- C++关于数字逆序输出的两种思路,及字符串逆序输出
- 特殊的数字 C++练习
- C++练习之 统计英文字母,空格,数字和其他字符的个数
- C/C++预习:数字逆序输出(2,折半)
- C++ 实现求一串数字的逆序数{线性代数里的逆序数}
- (c++)输入10个数字,然后逆序输出。
- 递归练习:逆序输出一个十进制数的各位数字
- (c++)给出一个不多于5位的整数,要求 1、求出它是几位数 2、分别输出每一位数字 3、按逆序输出各位数字,例如原数为321,应输出123
- 【LeetCode008-009算法/编程练习C++】string转int(atoi),判断数字是否是回文
- C++中逆序输出字符串和数字
- [C++]练习使用链表逆序存储的两个数相加
- [C++]练习使用链表逆序存储的两个数相加
- C++ 冒泡算法 练习
- C++中判断字符串是否全部由数字组成
- C++ 练习及点评(1)
- 面试题之金山_函数练习3_数值转换并输出数值中各个数字的个数(从低位到高位,输出转换后数值的各个数字个数)
- c++ 选择排序 练习
- 从易到难编写C++程序,(1)问题:把键盘输入的字符串逆序输出。
- C++ 冒泡算法 练习
- C++ 练习及点评(1)