Java Solution for Reverse Integer


  • 0
    W

    Re: Reverse Integer

    Algorithm
    1, My idea is to convert int value of the x to a string variable num which can be reversed each character every time.
    2, I use an exception to check whether the generated number overflowed or not.

    class Solution {
    public int reverse(int x) {
    String num = Integer.toString(x);
    int length = num.length() - 1;
    int result = 0;
    StringBuffer sb = new StringBuffer();
    if(x < 0) {
    num = num.substring(1);
    length--;
    sb.append("-");
    }
    for (int i = length; i >= 0 ; i--) {
    sb.append(num.charAt(i));
    }
    try {
    result = Integer.valueOf(sb.toString());
    } catch (java.lang.NumberFormatException e) {
    result = 0;
    }
    return result;
    }
    }

    Complexity Analysis

    Time complexity: O(n).


  • 0
    W

    Algorithm
    1, My idea is to convert int value of the x to a string variable num which can be reversed each character every time.
    2, I use an exception to check whether the generated number overflowed or not.

    public int reverse(int x) {
    	String num = Integer.toString(x);
    	int length = num.length() - 1;
    	int result = 0;
    	StringBuffer sb = new StringBuffer();
    	if (x < 0) {
    		num = num.substring(1);
    		length--;
    		sb.append("-");
    	}
    	for (int i = length; i >= 0; i--) {
    		sb.append(num.charAt(i));
    	}
    	try {
    		result = Integer.valueOf(sb.toString());
    	} catch (java.lang.NumberFormatException e) {
    		result = 0;
    	}
    	return result;
    }
    

    Complexity Analysis

    Time complexity: O(n).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.