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