本文共 1223 字,大约阅读时间需要 4 分钟。
题目:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:Input: 123 Output: 321Example 2:
Input: -123 Output: -321Example 3:
Input: 120 Output: 21Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解释:
题目要求我们是在32位的环境中解决问题??这如何知道是不是超出范围?辣鸡题目… python代码:class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ y=0 if x<0: x=str(x)[1:] y=-int(x[::-1]) else: y=int(str(x)[::-1]) if y<-2**31 or y>2**31-1: y=0 return y
c++代码:
#include#include #include using namespace std;class Solution { public: int reverse(int x) { long result=0; bool flag=false; if (x<0) flag=true; x=abs(x); string s=to_string(x); std::reverse(s.begin(),s.end()); result=atol(s.c_str()); if (result INT_MAX) return 0; return flag?-result:result; }};
总结:
转载地址:http://urlcn.baihongyu.com/