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;
    }
}
相关推荐
karry_k5 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k5 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
vibecoding日记6 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr21389 小时前
Verilog参数化游程编码RLE模块
算法
SamDeepThinking9 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
望易9 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
她的男孩11 小时前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
复杂网络13 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
荣码13 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python