leetcode 7. Reverse Integer

//Reverse digits of an integer.
//Example1: x = 123, return 321
//Example2: x = -123, return -321 

public class Solution {
	
	public static void main(String[] args) {
		int a =   100;
		int result = reverse(a);
		System.out.println(result);
	}
	
	 public static int reverse(int x) {
		 int result = 0;
		 String res = "";
		 String s = Integer.toString(x);
		 boolean flag = false;								//第一位是符号还是数字的标志
		 if(Character.isDigit(s.charAt(0))){				//判断第一位是符号还是数字
			 for(int i = s.length()-1;i>=0;i--){			//根据第一位采用不同的操作
				 res = res+s.charAt(i);
			 }
		 }else{
			 for(int i = s.length()-1;i>0;i--){
				 res = res+s.charAt(i);
			 }
			 flag = true;									//如果第一位是负号则改变flag
		 }
		 try{
			 result = Integer.parseInt(res);
		 }catch(Exception e){								//如果有数字越界问题,就返回0(题目中没有提到这一点。。。)
			 return 0;
		 }
		 if(flag == true){									//根据flag调整结果
			 result = -result;
		 }
		 return result;
	 }
    
}


你可能感兴趣的:(LeetCode)