原文链接

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.

class Solution1 {
public int reverse(int x) {
while (x % 10 == 0) {
x /= 10;
}
boolean tag = false;
if (x < 0) {
tag = true;
x = x * -1;
}
String s = String.valueOf(x);
char[] ch = s.toCharArray();
for (int i = 0;i < ch.length;i++) {
int k = ch.length - i - 1;
if (k < ch.length / 2) break;
char cc = ch[i];
ch[i] = ch[k];
ch[k] = cc;
}
String re = String.valueOf(ch);
int RI = Integer.valueOf(re);
if (tag) RI = RI * -1;
System.out.println(RI);
return RI;
}
}
/*
* 1. 前几天刚做了字符反转的,想当然就以为可以直接拿来用。结果却和出题人意图相差甚远.Solution1的方案对于小部分的测试数据可行,但是当前的状态是行不通的,也没有继续对此进行修改完善.
* 2. 一开始做的时候下面的Solution思路类似,但是因为对算法的逻辑思路不是很透彻,写出来的代码肯定很杂乱繁琐。下面的这个解题思路有参考到Discussion中的一个答案.
* 3. 昨晚做出来之后一直不晓得哪里出错了,没有意识到int类型的边界范围,还特别纳闷为啥断点跟踪的时候1534236469这个数字最后一下子就变了.根本没有考虑过怎么处理"int类型数据溢出"问题
* 上网搜索了一下之后才晓得怎么判断int类型问题。https://www.cnblogs.com/hesiyi/p/6963435.html
*
* */
class Solution {
public int reverse(int x) {
int sum = 0;
int t = 0;
while (x != 0) {
if ((sum * 10L) > Integer.MAX_VALUE || (sum * 10L) < Integer.MIN_VALUE)
return 0;
sum = sum * 10 + x % 10;
x = x / 10;
}
return sum;
}
}
public class ReverseInteger {
public static void main(String[] args) {
Solution1 solu = new Solution1();
int kkk = solu.reverse(-214748364); // -2147483648,1534236469
System.out.println(kkk);
}
}

关于int类型数据溢出的问题,移步博客:java-int数据的溢出

最新文章

  1. 并发编程 01—— ThreadLocal
  2. 使用Ogre::ManualObject 绘制自定义图形
  3. http 301 和 302 的区别!
  4. Java代码规范
  5. [Bootstrap]7天深入Bootstrap(1)入门准备
  6. Python基本概念及零碎知识点
  7. mysql performance schema的即时诊断工具-邱伟胜
  8. ffmpeg编译 --enable :没有命令
  9. Spark RDD概念学习系列之RDD的容错机制(十七)
  10. MTU of IPV4 and IPV6
  11. css 选择器 (学习笔记)
  12. 常见的磁盘I/O和网络I/O优化技巧
  13. C++类(Class)总结
  14. Bootstrap响应式导航
  15. java异步编程降低延迟
  16. DevExpress Windows 10 UWP Controls新版亮点
  17. java - 线程等待与唤醒
  18. 洛谷P4211 LCA
  19. Document对象中的一些重要的属性和方法(笔记)
  20. webapi Model Validation 模型验证

热门文章

  1. 基于Django的Rest Framework框架的视图组件
  2. Azure Sphere Development Environment Setup
  3. 【Nginx】Nginx反向代理转发Host设置
  4. activiti5初识
  5. 【shell脚本】优化内核参数===
  6. 10-Django中间件
  7. 邮件hMailServer +Foxmail 安装使用教程
  8. MVC过滤器:自定义异常过滤器使用案例
  9. python-execjs(调用js)
  10. Linux网络——配置网络之ifconfig家族命令