1.求N的階乘
a) 迭代算法
private static int jiecheng(int n) {
if (n <= 0) return 0;
int f1 = 1;
int product = f1;
// 5*4*3*2*1
for (int i = 1; i < n + 1; i++) {
product = product * f1;
f1 = f1 + 1;
}
return product;
}
b)遞歸算法
public long diGui(int n){
if(n==1){
return 1;
}else{
return n*diGui(n-1);
}
}
2、寫一個方法,要求:輸入一個字符串ABCDEFG,要求倒序輸出GFEDCBA:
public String formatString(String s){
//用for倒序循環(huán),取char類型的方法實(shí)現(xiàn)
for(int i=s.length()-1;i>=0;i--){
System.out.print(s.charAt(i));
}
return s;
}
3.不使用臨時變量交換兩個數(shù)
static void funSwapTwo(int a, int b) {
a = a ^ b;
b = b ^ a;
a = a ^ b;
System.out.println(a + " " + b);
}
4.判斷一個數(shù)是否為素數(shù)
static boolean funIsPrime(int m) {
boolean flag = true;
if (m == 1) {
flag = false;
} else {
for (int i = 2; i <= Math.sqrt(m); i++) {
if (m % i == 0) {
flag = false;
break;
}
}
}
return flag;
}
5.問題: 將一個整數(shù)轉(zhuǎn)換成字符串,要求不能使用系統(tǒng)調(diào)用。
ps:如果是把字符串轉(zhuǎn)換成數(shù)字的話要用到 char a='6',a-'0';
6.問題:反轉(zhuǎn)字符串
開始時想到的反轉(zhuǎn)算法非常簡單,就是利用折半法,把前后對應(yīng)位置的字符互換。但該算法沒有考慮速度和空間的優(yōu)化。
7.問題:字符串拷貝
8.問題:字符子串刪除
9.問題:在一個字符串str中查找一個子串sub,不使用任何的系統(tǒng)調(diào)用。
10.問題:編寫一個高效的函數(shù),找到字符串中首個非重復(fù)字符。例如:total 中的 首個非重復(fù)字符是 o,teeter是 r。討論算法的效率。
解答:此問題是字符串操作的經(jīng)典問題,考察的主要是查找的效率和實(shí)現(xiàn)的思路??梢允褂靡话愕乃悸罚顗牡臅r間復(fù)雜度是O(n^2),顯然不是好的解法。
問題:查找兩個字符串的公共子串。
ps 不是連續(xù)子串