Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

Subscribe to see which companies asked this question

第一反應把代碼寫成:

package leetcode;

public class Solution {
	public static int reverse(int x) {
		String s = Integer.toString(x);
		int len = s.length();
		String str="";
		if (x < 0) {// 說明含有負號
			str="-";
			for (int i = len-1; i>=1; i--) {
				str=str+s.charAt(i);
			}
		} else {
			for (int i = len-1; i>=0; i--) {
				str=str+s.charAt(i);
			}
		}
		int result=Integer.valueOf(str);
		return result;
	}

	public static void main(String[] args) {
		System.out.println(reverse(1534236469));

	}

}
結果出現:

正好是十位數的時候的問題,代碼中用到的Integer.valueOf是強制轉換string到int,但是十位好過了int的數據範圍,所以報錯了。

package leetcode;

public class Solution {
	public static int reverse(int x) {
		long result = 0;
		while (x != 0) {
			result = (result * 10) + (x % 10);
			if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {// 時刻檢查,要求result不可以超出範圍
				return 0;
			}
			x = x / 10;
		}
		return (int) result;
	}

	public static void main(String[] args) {
		System.out.println(reverse(1534236469));

	}

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章