Reverse an Integer

Problem:

Problem statement: Reverse a given integer input.

Solution:

public class ReverseInteger {

	public static void main(String args[]) {
		System.out.println(reverse(-123));
	}
	
	public static int reverse(int x) {
        int rev = 0;
        do {
        	int dig = (int) Math.floor(1 + Math.log(Math.abs(x))/Math.log(10));
        	rev += x%10 * Math.pow(10, dig-1);
        	x = x/10;
        }while( x != 0);
        return rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE ? 0 : rev;
    }
}

Explanation:

Find the number of digits.

Time and Space:

Time: o(1) and Space O(1)
Explanation:

(Visited 13 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
14 + 27 =