Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

java - How are the numbers stored, called, and added in this short recursion example?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may find it easier to reason about this code if you swap the two operands of the +, that is, change it to read:

return (n % 10) + sumDigits(n / 10)

i.e.

sumDigits(115) = 5 + sumDigits(11)
 sumDigits(11) = 1 + sumDigits(1)
  sumDigits(1) = 1

so expanding that:

sumDigits(115) = 5 + (1 + sumDigits(1))
               = 5 + 1 + 1
               = 7

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...