博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
7. Reverse Integer(python+cpp)(int范围的问题)
阅读量:3703 次
发布时间:2019-05-21

本文共 1223 字,大约阅读时间需要 4 分钟。

题目:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123 Output: 321

Example 2:

Input: -123 Output: -321

Example 3:

Input: 120 Output: 21

Note:

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/

你可能感兴趣的文章
求一个关于MyCat的博客名(1)
查看>>
Mycat启动日志报错:XML document structures must start and end within the same entity.
查看>>
div内的元素垂直居中和水平居中
查看>>
Freemarker引入外部Css样式
查看>>
记一次Oracle数据库数据找回的过程
查看>>
Vue的安装
查看>>
Oracle数据库错误Update数据恢复
查看>>
Sql Server数据库查询死锁和解决死锁
查看>>
Nginx配置文件
查看>>
SpringCloud组件替代方案
查看>>
Mysql实现乐观锁
查看>>
SpringBoot项目自定义Filter过滤器
查看>>
Springboot项目实现自定义拦截器
查看>>
德鲁伊后台监控配置
查看>>
正向代理和反向代理
查看>>
Stream常用方法使用案例
查看>>
Log4j日志的配置文件
查看>>
Slf4j和logback日志组合
查看>>
Mysql的读写分离和主从复制过程概述
查看>>
数据库搭建主从复制结构(主写从读)
查看>>