007. Reverse Integer
2024-09-04 21:06:35
题目链接:https://leetcode.com/problems/reverse-integer/description/
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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
思路:
- 对待处理的整数X,拷贝一份并命名为 copy,取拷贝值的绝对值进行下述数据处理;
- 用长整型变量 ans 来存储翻转后的数值, ans变量赋初值为0; 当copy > 0 时对copy进行整除和取余操作:
- int cur = copy % 10; // 当前处理的数位的值
- ans = ans * 10 + cur;
- copy = copy / 10;
- 对求得的ans值进行范围检验;
- 若X值为正数,则返回ans;若X值为负数,则返回 -ans 。
编码如下:
class Solution {
public:
int reverse(int x) {
// 若数值不在 [−2^31, 2^31 − 1]范围内,则返回0
//if (x < (1 << 31) || x > (~(1 << 31))) return 0; // 若x属于[-9, 9]这个范围内,则返回x
if (- < x && x < ) return x; // 其他情况
long int ans = ;
int copy = (x >= ? x : -x); while (copy > )
{
int cur = copy % ; // 当前处理的数位值
ans = ans * + cur;
copy = copy / ;
} ans = (x >= ? ans : -ans);
if (ans < ( << ) || ans > (~( << ))) return ; return static_cast<int>(ans);
}
};
最新文章
- java.sql.SQLException: Incorrect string value:
- 【BZOJ 1492】【NOI 2007】货币兑换Cash
- Asp.Net Web API 2第十四课——Content Negotiation(内容协商)
- vim编辑器配置修改
- 使用ultramon调整任务栏高度
- Js跳出循环
- 将非WPF window设为 WPF Window的Owner
- Fixflow引擎解析(二)(模型) - BPMN2.0读写
- Android开发UI之Toast的使用
- 404 Not Found The requested URL * was not found on this server
- Android Imageview 图片居左居右,自定义圆角
- proc文件系统探索 之 根目录下的文件[三]
- Cocos2D iOS之旅:如何写一个敲地鼠游戏(九):创建动画
- JAVA 中的命名规则
- 【vue】钩子函数生命周期
- PostgreSQL之连接数修改
- [knownledge][latex] LaTex入门
- 记录:tf.saved_model 模块的简单使用(TensorFlow 模型存储与恢复)
- Graph 卷积神经网络:概述、样例及最新进展
- linux两种类型服务管理