2014年4月7日 星期一

[LeetCode] Reverse Integer

Problems:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Solution: O(n) 
public class Solution {
    public static int reverse(int x) {
        int index = 1;
        int value = x;
        if(x<0){
            index = -1;
            value = -x;
        }
        int ret = 0;
        while(value >0){
            int v = value%10;
            ret = ret*10 + v;
            value/=10;
        }
        return ret*index;
    }
}     
Key concept: we should always consider last digit is 0 and will overflow after revert but the solution only concern revertable

沒有留言:

張貼留言