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.

Solution 1: comparison to handle overflow

class Solution {
public int reverse(int x) {
int res = 0;
while (x != 0) {
int cur = res;
res = 10 * res + x % 10;
if (cur != res / 10) {
return 0;
}
x /= 10;
}
return res;
}
}

Solution 2: use Long to handle overflow

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

最新文章

  1. yii2 解决POST 400错误
  2. mac 下载安装 IntelliJ IDEA Tomcat
  3. Careercup - Google面试题 - 4877486110277632
  4. CentOS FireFox Flash Player
  5. Base64.java 工具类
  6. FineUploader 学习笔记
  7. Android Studio编译FBReaderJ
  8. selenium.common.exceptions.TimeoutException: Message: Screenshot: available via screen
  9. 新博客——That
  10. python摸爬滚打之day030----进程
  11. 微信小程序+微信管理后台+微信用户前台
  12. make: *** /lib/modules/3.10.0-327.el7.x86_64/build: 没有那个文件或目录。 停止。
  13. PAT 1046 划拳(15)(代码)
  14. Vue 使用 prerender-spa-plugin 添加loading
  15. Jmeter接口自动化测试 (四)(持续构建)
  16. linux搜索命令之find和grep
  17. Eclipse内存讲解,eclipse.ini设置
  18. hadoop HA集群搭建步骤
  19. Android四种跨进程通信
  20. 记录一次teamview无法远程连接对方teamview的过程

热门文章

  1. 开始新建AEM站点-周末教程
  2. Feign整合测试
  3. Lambder笔记
  4. Ubuntu的奇技淫巧
  5. redis在linux中的安装启动
  6. 堆--P1168 中位数
  7. c语言中assert的用法
  8. 后台用Hbase对表单数据实现增删改查遇到的问题
  9. centos7 安装gdb (调试nginx)
  10. 判断1/N是否为无限小数