LeetCode 7. Reverse Integer
原题链接在这里:https://leetcode.com/problems/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.
题解:
x%10加到res中.
负数-123 mod 10 = -3, 所以不用担心负数.
注意corner case, e.g. 2133....99, 反过来9开头时就冒了Integer.MAX_VALUE了.
Time Complexity: O(n), n是x的位数. Space: O(1).
AC Java:
1 class Solution { 2 public int reverse(int x) { 3 int res = 0; 4 while(x != 0){ 5 int cur = x % 10; 6 x /= 10; 7 if(res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && cur > 7)){ 8 return 0; 9 } 10 11 if(res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && cur < -8)){ 12 return 0; 13 } 14 15 res = res * 10 + cur; 16 } 17 18 return res; 19 } 20 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步