Tuesday, February 11, 2014

Reverse Integer

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Solution:
Basic implementation question.
Corner cases: 1. 100-->001. 2. overflow. 
public class Solution {
    public int reverse(int x) {
        String str = String.valueOf(x);
        if(x < 0){ 
            str = str.substring(1);
        }
        String reverseStr = reverseString(str);
        if(x < 0){
            reverseStr = "-" + reverseStr;
        }
        return Integer.parseInt(reverseStr);
    }
    public String reverseString(String str){
        int first = 0;
        int last = str.length() - 1;
        while(first < last){
            str = swap(str, first, last);
            first++;
            last--;
        }
        return str;
    }
    public String swap(String str, int first, int last){
     char[] c = str.toCharArray();
        char temp = c[first];
        c[first] = c[last];
        c[last] = temp;
        return new String(c);
    }
}

No comments:

Post a Comment