LeetCode Question 7 Reversed Integer

Given a 32-bit signed integer, invert the numbers in the integer.

Example 1:

Input: 123
 Output: 321

 Example 2:

Input: -123
 Output: -321

Example 3:

Input: 120
 Output: 21

Notice:

Suppose that our environment can only store 32-bit signed integers in the range [−2 31 , 2 31  − 1]. According to this assumption, if the inverted integer overflows, 0 is returned.

Idea 1: Use the reverse() method of StringBuilder that comes with java.

public static int reverse1(int x) {
		int tmp = Math.abs(x);
        StringBuilder sBuilder = new StringBuilder();
        sBuilder.append(tmp);
        sBuilder = sBuilder.reverse();
        if(Long.parseLong(sBuilder.toString())>Integer.MAX_VALUE) {
        	return 0;
        }
        return x>0?Integer.parseInt(sBuilder.toString()):-Integer.parseInt(sBuilder.toString());
    }

Idea 2: Calculate the reversed number, pay attention to the overflow problem

public static int reverse2(int x) {
		int tmp = Math.abs(x);
		long reverse=0;
		while (tmp>0) {
			reverse=reverse*10 + tmp%10;
			if(reverse>Integer.MAX_VALUE) {
				return 0;
			}
			tmp=tmp/10;
		}
		return (int)(x>0?reverse:-reverse);
	}
GitHub address: https://github.com/xckNull/Algorithms-introduction

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324778427&siteId=291194637