• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 知识库 知识库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

java面试题2020java递归

武飞扬头像
xhjyxxw
帮助0

知行礼动

大家好,今日小经来聊聊一篇关于java面试题2020,java递归的文章,现在让我们往下看看吧!

1、/** * 概念介绍: * 递归是一种方法(函数)调用自已编程技术。

2、 * 递归就是程序设计中的数学归纳法。

3、 * 例如:tri(n)=1 if n=1 * tri(n)=n tri(n-1) if n>1 * 可能while循环方法执行的速度比递归方法快,但是为什么采用递归呢。

4、 * 采用递归,是因为它从概念上简化了问题,而不是因为它提高效率。

5、 */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Recursion {//求三角数字的递归算法:1,3,6,10,15,21, ...... static int theNumber; public static void main(String[] args) throws IOException { System.out.print("Enter a number: "); theNumber = getInt(); //使用递归时调用,默认 int theAnswer = triangle(theNumber); //使用非递归时调用 //int theAnswer=triangle2(theNumber); System.out.println("Result: " theAnswer); } public static int triangle(int n) {//递归方法,循环调用 if (n == 1) { return 1; } else { return (n triangle(n - 1)); } } public static int triangle2(int n) {//非递归方法 int total = 0; while (n > 0) { total = total n--; } return total; } public static String getString() throws IOException { InputStreamReader isr = new InputStreamReader(***.in); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); return s; } public static int getInt() throws IOException { String s = getString(); return Integer.parseInt(s); } } /** * 运行结果: * Enter a number: * 3 * Result: 6 */ /** * 总结: * 使用非递归的方式更简洁,更易懂,运行效率更高,为什么还要用递归的算法呢。

6、 * 递归使规模逐渐降低的方式解决问题,以这种统一的方式解决足够复杂的问题。

7、 */尚硅谷分享、务实、专业、良心坚持做良心教育支持良心教育,支持尚硅谷递归算法,你只需要知道算法规则从根源上理解他,剩下的你只需要多做练习题就ok了!。

本文到此分享完毕,希望对大家有所帮助。

这篇好文章是转载于:知行礼动

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 知行礼动
  • 本文地址: /knowledge/detail/tanhefhhhb