Sunday, September 22, 2013

Reverse Integer

Q:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

A:
思路比较SB,就是利用一个数组, 存下所有 mode 10 的结果。然后再乘起来。

public class Solution {
    public int reverse(int x) {
        int res = 0;
        while (x != 0) { // don't care positive or negetive
            if(x<0 && res<Integer.MIN_VALUE/10)
                return 0;
            if(x>0 && res>Integer.MAX_VALUE/10)
                return 0;
            res = res * 10 + x % 10; // get lowest digit then multi 10
            x /= 10;
        }
        return res;
    }
} 

Learned:
1: 也有人,不用数组, 用queue来存储mod 10的结果。

2: 自己这里是用了throw exception 来处理溢出。
但是,题目建议 自己多写个参数。
Tiger暂时不知道,怎么更改参数,让OJ调用。  回头再看吧。?????????????????

3:    java里的mod 运算, 是可以给出负值的。

        System.out.println(  -123 % 10);          打印             -3
        System.out.println(  4 % 10);        打印                      4
        System.out.println(  -4 % 10);       打印                   -4
       












No comments:

Post a Comment