LeetCode 7 Reverse Integer(C,C++,Java,Python)
来源:互联网 发布:北大青鸟编程调试软件 编辑:程序博客网 时间:2024/06/05 05:59
Problem:
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.
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.
Solution:
To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why?
Average Rating: 3.5 (360 votes)
题目大意:
解题思路:
Java源代码(用时228ms):
public class Solution { public int reverse(int x) { int flag=x>0?1:-1,res=0; x=x>0?x:-x; while(x>0){ if(res*10.0 + x%10 > 2147483647)return 0; res = res*10+x%10; x/=10; } return res*flag; }}
C语言源代码(用时10ms):
int reverse(int x) { int flag=x>0?1:-1,res=0; x=x>0?x:-x; while(x>0){ if((2147483647.0-x%10)/10<res)return 0; res=res*10+x%10; x=x/10; } return res*flag;}
C++源代码(用时13ms):
class Solution {public: int reverse(int x) { int flag=x>0?1:-1,res=0; x=x>0?x:-x; while(x>0){ if(res*10.0+x%10 > 2147483647)return 0; res = res*10+x%10; x/=10; } return res*flag; }};
Python源代码(用时72ms):
class Solution: # @param {integer} x # @return {integer} def reverse(self, x): flag=1 if x>0 else -1 x=x if x>0 else -x res=0 while x>0: if res*10.0 + x%10 > 2147483647:return 0 res = res*10+x%10 x/=10 return res*flag
- LeetCode 7 Reverse Integer(C,C++,Java,Python)
- [LeetCode] 007. Reverse Integer (Easy) (C++/Java/Python)
- 【leetcode】7. Reverse Integer(Python & C++)
- 【leetcode c++】Reverse Integer
- LeetCode Reverse Integer(C)
- reverse integer 之 c c++ python java
- 【leetcode-7】Reverse Integer(C语言)
- 【leetcode-7】Reverse Integer(C语言)
- LeetCode-7-Reverse Integer(C语言实现)
- [C++]LeetCode: 17 Reverse Integer
- LeetCode::Reverse Integer C语言
- C实现 LeetCode->Reverse Integer
- [leetcode]Reverse Integer C语言
- Leetcode c语言-Reverse Integer
- Reverse Integer Leetcode Python Java
- 【LeetCode】【Python】【C++】7. Reverse Integer代码实现
- 【LeetCode 7】Reverse Integer(Python)
- [C++]LeetCode 7:Reverse Integer(翻转整数)
- poj 3187 Backward Digit Sums (全排列)
- Linux统计文件数量
- Reverse Integer - LeetCode
- UIView,UIButton,UIImageView等设置圆角,设置阴影,设置边框的方法
- CSUOJ 1600 Twenty-four point (判断24点,另附给出表达式版)
- LeetCode 7 Reverse Integer(C,C++,Java,Python)
- (转) C++ 静态成员和函数的总结(不知道原创在哪里=。=)
- Spring ApplicationContext配置文件的路径配置方式
- 第五章作业5.18
- iOS 禁止横屏
- 阅读笔记——基于字典学习的图像分类方法总结
- 4.17
- Linux makefile 教程 非常详细,且易懂
- Wdatepicker日期控件的使用指南