Example1: x = 123, return 321
Example2: x = -123, return -321
Be careful about some interesting cases. i.e.negative number, overflow case.
1 public int reverse(int x) { 2 if (x >= -9 && x <= 9){ 3 return x; 4 } 5 6 boolean isNeg = false; 7 if (x < 0){ 8 isNeg = true; 9 x = 0 - x; 10 } 11 12 double result = 0; 13 14 while(x > 0){ 15 result = result * 10 + x % 10; 16 x = x / 10; 17 } 18 19 if (isNeg){ 20 return -result < Integer.MIN_VALUE ? 0 : -(int)result; 21 } 22 else{ 23 return result > Integer.MAX_VALUE ? 0 : (int)result; 24 } 25 }
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
I use split to change it an word array, or you can use toCharArray() to change it to char array.
1 public String reverseWords(String s) { 2 StringBuffer result = ""; 3 String[] array = s.split(" "); 4 for (int i = array.length - 1; i >= 0; i --){ 5 String temp = array[i].trim(); 6 if (temp.equals("") == false){ 7 if (i != array.length - 1){ 8 result += " " + temp; 9 } 10 else{ 11 result += temp; 12 } 13 } 14 } 15 return result.trim(); 16 }
原文:http://www.cnblogs.com/timoBlog/p/4735861.html