题目链接: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);
}
};

最新文章

  1. java.sql.SQLException: Incorrect string value:
  2. 【BZOJ 1492】【NOI 2007】货币兑换Cash
  3. Asp.Net Web API 2第十四课——Content Negotiation(内容协商)
  4. vim编辑器配置修改
  5. 使用ultramon调整任务栏高度
  6. Js跳出循环
  7. 将非WPF window设为 WPF Window的Owner
  8. Fixflow引擎解析(二)(模型) - BPMN2.0读写
  9. Android开发UI之Toast的使用
  10. 404 Not Found The requested URL * was not found on this server
  11. Android Imageview 图片居左居右,自定义圆角
  12. proc文件系统探索 之 根目录下的文件[三]
  13. Cocos2D iOS之旅:如何写一个敲地鼠游戏(九):创建动画
  14. JAVA 中的命名规则
  15. 【vue】钩子函数生命周期
  16. PostgreSQL之连接数修改
  17. [knownledge][latex] LaTex入门
  18. 记录:tf.saved_model 模块的简单使用(TensorFlow 模型存储与恢复)
  19. Graph 卷积神经网络:概述、样例及最新进展
  20. linux两种类型服务管理

热门文章

  1. SCU 4584 tarjan+最大权闭合子图
  2. SpringData JPA 在解析实体类字段时驼峰自动添加下划线问题
  3. 搭建私有CA
  4. guava的一些用法
  5. yii框架学习(安装)
  6. mysql随机取出n条数据
  7. 4、路由事件 RoutedEvent
  8. vue模板语法下集
  9. matlab函数 bsxfun浅谈(转载)
  10. jq获取页面中checkbox已经选中的checkbox