7. Reverse Integer

题目描述:

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 Solution {
public int reverse(int x) {
int reversed = 0;
int pop = 0;
while(x!=0)
{
pop = x%10;
x = x/10; if(reversed>Integer.MAX_VALUE/10 || (reversed==Integer.MAX_VALUE/10 && pop>7)){
return 0;
} if(reversed<Integer.MIN_VALUE/10 || (reversed==Integer.MIN_VALUE/10 && pop<-8)){
return 0;
} reversed = reversed*10+pop; } return reversed;
}
}

在本题中,难点主要是有限整数的翻转和防止值溢出。

  • 对于有限整数的翻转,本题采用的方法是用循环,取余,再除以10的方法
  • 而对于栈溢出

根据如下公式:

采用:

if (reversed>Integer.MAX_VALUE || (reversed==Integer.MAX_VALUE && pop>7)

if(reversed<Integer.MIN_VALUE || (reversed==Integer.MIN_VALUE && pop<-8))

问题解法 二:

当然还有一种解法就是使用long型号数组,再转化成(int), 这里省去了复杂的公式判断;因为在int型中,如果不按照公式进行判断的话,就会溢出,缺点是由于测试数据并未超过long型号的长度,所以也能通过。

 public int reverse(int x) {
long res = 0;
while (x != 0) {
res = res * 10 + x % 10;
x = x / 10;
} if (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) {
return 0;
} else {
return (int)res;
}
}

最新文章

  1. VS2013 GIT 克隆远程仓库
  2. CTF中那些脑洞大开的加密(1)
  3. this关键字的使用
  4. ab apache Benchmarking中链接的写法 记得加上/
  5. C语言的printf输出格式控制
  6. 用一条SQL语句取出第 m 条到第 n 条记录的方法
  7. Learning Java IO indexes
  8. 实现CA证书创建及客户端申请证书
  9. 201521123031 《Java程序设计》第12周学习总结
  10. 【Luogu1501】Tree(Link-Cut Tree)
  11. 老婆大人 split,slice,splice,replace的用法
  12. (转)Spring4.0:@Configuration
  13. Nginx proxy_protocol协议
  14. 软件开发 [CJOJ 1101] [NOIP 模拟]
  15. 五、u-boot 启动流程---u-boot.lds
  16. Flex_概念
  17. pom.xml文件中,添加自定义参数Properties
  18. Jersey RESTful Web服务
  19. UGUI RectTransform
  20. 关闭window端口445

热门文章

  1. python接口自动化9-ddt数据驱动
  2. D3力布图绘制--节点自己连自己的实现
  3. EventBus 使用/架构/源码分析
  4. JBoss+eclipes之HelloWorld
  5. .net core使用NLog日志
  6. DesignPattern系列__09设计模式概述
  7. 定时器每隔10秒钟刷新一次jqgrid
  8. 一文解读Spring全家桶 (转)
  9. 记录C#-WPF线程中如何修改值
  10. MySQL数据库(一)索引