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 }

类似String to Integer (atoi)Reverse Bits.

posted @ 2016-01-18 15:48  Dylan_Java_NYC  阅读(144)  评论(0编辑  收藏  举报