原题链接在这里:https://leetcode.com/problems/reverse-integer/
题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
题解:
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:
public class Solution { public int reverse(int x) { long res = 0; while(x != 0){ res = res*10 + x%10; x /= 10; } if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE){ return 0; } return (int)res; } }
所有评论(0)