前几天遇到的笔试题,思路很简单,就是具体使用的方法忘了……我写了三种方法,和大家分享一下
//利用递归求余数
public int ReverseByInt(int a) {
System.out.print(a % 10);
if (a < 10) {
System.out.println();
return 0;
}
return ReverseByInt(a / 10);
}
//将整数转化成char数组进行反转
public void ReverseByString(int a) {
String s = String.valueOf(a);
char[] c = s.toCharArray();
for (int i = 0; i < (c.length - 1) / 2; i++) {
char temp = c[i];
c[i] = c[c.length - i - 1];
c[c.length - i - 1] = temp;
}
System.out.println(c);
}
//利用StringBuffer的revers方法反转
public void ReverseByBuffer(int a) {
StringBuffer s = new StringBuffer(Integer.toString(a));
s = s.reverse(); // 反转
System.out.println(s.toString());
}
public static void main(String[] args) {
Reverse m = new Reverse();
m.ReverseByInt(123456789);
m.ReverseByString(123456789);
m.ReverseByBuffer(123456789);
}
}