c语言程序超出int范围,C++-int类型整数超出范围后的处理

本文介绍了如何处理C++中32位整数反转时可能出现的溢出问题,通过示例代码和分析解释了当整数超出范围时,数值会如何变化,并提供了一种检查溢出的巧妙方法。
摘要由CSDN通过智能技术生成

最近做了一道题目:

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.

来源:https://leetcode.com/problems/reverse-integer/

先贴上自己丑陋的代码:

1 classSolution {2 public:3 int reverse(intx) {4 bool isNegative=false;5 if(x==0||xpow(2,31)-1)6 return 0;7 if(x<0){8 isNegative=true;9 x=-1*x;10 }11 while(x%10==0)12 x=x/10;13 int ans=0,temp;14 temp=x-(x/10)*10;15 while(x>=1&&ans=1)22 return 0;23 if(isNegative)24 an

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值