Java经典编程题

题目 1:斐波那契数列

题目要求 :编写一个方法,输入正整数n,输出斐波那契数列的第n项。斐波那契数列的定义是:F(0)=0F(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;
    }
}
相关推荐
孟陬6 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端
想用offer打牌6 小时前
一站式了解四种限流算法
java·后端·go
华仔啊6 小时前
Java 开发千万别给布尔变量加 is 前缀!很容易背锅
java
也些宝7 小时前
Java单例模式:饿汉、懒汉、DCL三种实现及最佳实践
java
Gorway7 小时前
解析残差网络 (ResNet)
算法
拖拉斯旋风7 小时前
LeetCode 经典算法题解析:优先队列与广度优先搜索的巧妙应用
算法
Wect7 小时前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript
Nyarlathotep01138 小时前
SpringBoot Starter的用法以及原理
java·spring boot
wuwen58 小时前
WebFlux + Lettuce Reactive 中 SkyWalking 链路上下文丢失的修复实践
java