在这个简短的递归示例中,数字是如何存储、调用和添加的? [英] How are the numbers stored, called, and added in this short recursion example?

查看:31
本文介绍了在这个简短的递归示例中,数字是如何存储、调用和添加的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,这不是家庭作业.我正在练习

First off, it's not homework. I'm practicing examples from http://codingbat.com/java/Recursion-1. Every time I think I'm beginning to understand recursion, I run into a problem that makes me realize I have no idea, and the only thing tutors or internet explanations ever say is that "the function calls itself until the base case is met."

public int sumDigits(int n) {
   if(n < 10) {
      return n;
   } else return sumDigits(n/10) + n % 10;
}

If I pass 115 to this on my computer, the output is 7 (as it should), but I don't understand how the program comes to this conclusion. Here is how I see it:

115 is not less than 10, so return the program with 115/10 (which is 11). 11 is not less than 10, so return the program with 11/10 (which is 1). Add this to 115%10 (which is 5). So how does this program get 7???

It seems like no matter how many examples I look at, I cannot find a pattern in how this works.

解决方案

Here is how it happens explained with a diagram

这篇关于在这个简短的递归示例中,数字是如何存储、调用和添加的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆