1,数字反转:
public static int reverse(int x) {
long n = 0;
while(x != 0)
{ n = n*10 + x%10;
x = x/10; }
return (int)n==n?(int)n:0;
}
2,二分换位反转
public static String reverseTestFive(String s) {
int start = -1;
int end = s.length();
char[] charArray = s.toCharArray();
while (start++ < end--) {
//交换首尾char值
char c = charArray[end];
charArray[end] = charArray[start];
charArray[start] = c;
}
return new String(charArray);
}
3、利用栈的先进后出
public static String reverseTestFour(String s) {
StringBuffer sb = new StringBuffer();
Stack stack = new Stack();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.isEmpty()) {
//stack会返回栈顶值,并且会把该值删除
sb.append(stack.pop());
}
return sb.toString();
}
4,利用StringBuilder方法进行反转
public static String reverseTestOne(String s) {
return new StringBuffer(s).reverse().toString();
}