简体   繁体   English

程序难以理解

[英]Program difficult to understand

I have a program and I don't understand its result. 我有一个程序,我不明白它的结果。 It gives me 110 , but I don't know how it's even possible. 它给了我110 ,但我不知道它怎么可能。 I call it only once. 我只称它一次。 For me, it should be 3?? 对我来说,它应该是3 ?? Thank you 谢谢

public class Test {
    public static String operator (int n) {
        return((n == 0) ? "" : operator(n / 2) + (n % 2));
    }

    public static void main(String[] args) {
        System.out.println(operator(6));
    }
}

The recursion in this function causes the middle to be repeatedly evaluated with the modulus of the original argument appended with each iteration. 此函数中的递归导致使用每次迭代附加的原始参数的模数重复计算中间值。 So follow the expansion of operator(6) 所以跟随运算符的扩展(6)

  1. operator(6) => operator(6/2)+(6%2) = operator(3) + "0" operator(6)=> operator(6/2)+(6%2)= operator(3)+“0”
  2. operator(3) => operator(3/2)+(3%2) = operator(1) + "1" operator(3)=> operator(3/2)+(3%2)= operator(1)+“1”
  3. operator(1) => operator(1/2) + (1%2) = operator(0) + "1" operator(1)=> operator(1/2)+(1%2)= operator(0)+“1”
  4. operator(0) = > "" operator(0)=>“”

The recursion ends at the 4th iteration, and the unwound result becomes "110" 递归在第4次迭代结束,展开的结果变为“110”

It's a simple recursive method, which can be expressed like this to make it more readable: 这是一个简单的递归方法,可以这样表达,使其更具可读性:

operator(0) = ""
operator(n) = operator(n / 2) + (n % 2)

So following those rules, operator(6) = "110" as follows: 因此遵循这些规则, operator(6) = "110"如下:

operator(6) = operator(6 / 2) + (6 % 2)
            = operator(3) + 0
            = operator(3 / 2) + (3 % 2) + 0
            = operator(1) + 1 + 0
            = operator(1 / 2) + (1 % 2) + 1 + 0
            = operator(0) + 1 + 1 + 0
            = "" + 1 + 1 + 0
            = "110"

operator returns a string. operator返回一个字符串。 So the result of operator(n/2)+(n%2) is adding (concatenating) the string from operator(n/2) with the value of (n%2) which is automatically converted to a string so that it can be concatenated. 这样的结果operator(n/2)+(n%2)是添加(串联)从字符串operator(n/2)与值(n%2)其被自动地转换为字符串,使得它可以被连接起来。

Try changing operator to return int and changing the line to read: 尝试更改operator以返回int并将行更改为:

return((n == 0) ? 0 : operator(n/2)+(n%2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM