題目 1:斐波那契數列
題目要求:編寫一個方法,輸入正整數n
,輸出斐波那契數列的第n
項。斐波那契數列的定義是:F(0)=0
,F(1)=1
, 當n > 1
時,F(n)=F(n - 1)+F(n - 2)
。
答案:
public class Fibonacci {public static int fib(int n) {if (n == 0) return 0;int a = 0, b = 1;for (int i = 2; i <= n; i++) {int c = a + b;a = b;b = c;}return b;}
}
題目 2:字符串反轉
題目要求:編寫一個方法,將輸入字符串進行反轉。
答案:
public class ReverseString {public static String reverse(String s) {return new StringBuilder(s).reverse().toString();}
}
題目 3:判斷素數
題目要求:編寫一個方法,判斷輸入的正整數是否為素數(質數)。
答案:
public class PrimeChecker {public static boolean isPrime(int n) {if (n <= 1) return false;for (int i = 2; i <= Math.sqrt(n); i++) {if (n % i == 0) return false;}return true;}
}
題目 4:冒泡排序
題目要求:編寫一個方法,使用冒泡排序算法對整數數組進行升序排序。
答案:
public class BubbleSort {public static void sort(int[] arr) {int n = arr.length;for (int i = 0; i < n - 1; i++) {for (int j = 0; j < n - i - 1; j++) {if (arr[j] > arr[j + 1]) {int temp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = temp;}}}}
}
題目 5:計算階乘
題目要求:編寫一個方法,計算輸入正整數n
的階乘n!
。
答案:
public class Factorial {public static int factorial(int n) {if (n == 0) return 1;int result = 1;for (int i = 1; i <= n; i++) {result *= i;}return result;}
}