zoukankan      html  css  js  c++  java
  • 递归的典型用法

    一:递归的概念

    就是在自己的方法中调自己的方法,这样做可以提高效率。

    二:经典案例

     1 /**
     2  * 
     3  */
     4 package com.paic.recursion;
     5 
     6 import java.io.File;
     7 
     8 /**
     9  * @author Administrator 使用递归的几个案例
    10  */
    11 public class RecursionDemo {
    12 
    13     // 1:使用递归求1+2+3+4+5
    14     public static int getSum(int i) {
    15         if (i == 5) {
    16             return i;
    17         }
    18         return getSum(i + 1) + i;
    19     }
    20 
    21     // 2:使用递归,反转整数12345
    22     public static void reverseNum(int i) {
    23         if (i > 0 && i < 10) {
    24             System.out.println(i);
    25         } else {
    26             int num = i % 10;
    27             System.out.print(num);
    28             reverseNum(i / 10);
    29         }
    30     }
    31 
    32     // 3:使用递归,反转字符串abcdef
    33     public static String reverseString(String str) {
    34         if (str == null || str.length() < 1) {
    35             return str;
    36         }
    37         return reverseString(str.substring(1, str.length())) + str.charAt(0);
    38     }
    39 
    40     // 4:递归输出一个目录下的文件
    41     public static void printDir(File dir) {
    42         if (!dir.exists()) {
    43             return;
    44         }
    45         if (dir.isDirectory()) {
    46             File[] lists = dir.listFiles();
    47             for (File f : lists) {
    48                 printDir(f);
    49             }
    50         } else if (dir.isFile()) {
    51             System.out.println(dir.getAbsolutePath());
    52         }
    53     }
    54 
    55     // 测试
    56     public static void main(String[] args) {
    57         File dir = new File("F:/test");
    58         System.out.println(getSum(1));
    59         reverseNum(12345);
    60         System.out.println(reverseString("abcd"));
    61         printDir(dir);
    62     }
    63 }

    以上代码均已经验证!

  • 相关阅读:
    input 去除边框
    分页封装
    python后端继承序列化,不同访问形式返回不同结果
    解决vue前端不显示自定义字段
    Vue 获取后端多对多关联表信息
    vue 前段增删改查代码规范
    前段增删改查的应用
    ant-design-vue基础
    python 后端 数据库的创表及增删改查 简单使用
    配置Uwsgi+Nginx+Django+Vue
  • 原文地址:https://www.cnblogs.com/warrior4236/p/5690094.html
Copyright © 2011-2022 走看看