栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

基本Java递归方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基本Java递归方法

一个递归函数是一个函数,它的实现引用自身。以下是一些有趣的示例:

public class Inception {   public void dream() {      boolean enoughDreaming = false;      //Some pre logic below to check if it's high time to stop dreaming recursively      ...      ...      if(!enoughDreaming) {dream(); //Dream inside a Dream      }   }}

解决问题的方法:

public class GeometricSequence {    public static void main(String[] args) {        //Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.        System.out.println(findNthNumber(5, 1, 2));    }    public static int findNthNumber(int n, int count, int res) {        return ((count == n)) ? res : findNthNumber(n, count+1, res *3);    }}

编辑

上面的类使用“ int”,它仅对少量数字有效(由于Integer Overflow问题)。下列类别适用于所有类型/数字:

public class GeometricSequence {    public static void main(String[] args) {        //Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.        System.out.println(findNthNumber(2000, 1, new BigInteger("2")));    }    public static BigInteger findNthNumber(int n, int count, BigInteger res) {        return ((count == n)) ? res : findNthNumber(n, count+1, res.multiply(new BigInteger("3")));    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/573868.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号