最近发现笔试中常常遇到反字符串问题
其解决思路基本是递归
直接上代码
public class InverseString {
public static void main(String[] args) {
String s = "sdfjwheugaqwq";
String reverseString = test1(s);
System.out.println("the reversString of "+ s+" is :"+reverseString);
}
private static String test1(String s) {
if(s.length()>1) return test1(s.substring(1))+s.charAt(0);
return s;
}
}
运行结果
另外,StringBuffer 其实封装了反字符串的方法 reverse();
private static String test2(String s) {
StringBuffer stringBuffer = new StringBuffer(s);
return stringBuffer.reverse().toString();
}
输出结果是一样的
eg2: 手写一个阶乘算法,用户输入一个数字(1<n<20),结果返回该数字阶乘;
思路1, for循环(推荐指数:2颗星)
public static int Factorial(int p0){
int sum = 1;
for(int i = p0; i>0;i--){
sum *= i;
}
return sum;
}
思路2, 递归(推荐指数:5颗星)
public static int Factorial(int p0){
if(po>1) return test2(po-1)*po;
return po;
}