How does returning an || statement work in java?

前端 未结 7 647
北荒
北荒 2021-01-29 16:04

I\'m new to programming so I have been working through the exercises at CodingBat.com. In the Recursion-2 section, there is a problem I wasn\'t able to solve (recursively) so I

7条回答
  •  孤街浪徒
    2021-01-29 16:40

    return helper(start + 1, nums, sum1 + nums[start], sum2)
            || helper(start + 1, nums, sum1, sum2 + nums[start]);
    

    returns true if either call to helper() returns true. Here is the same code written a different but functionally equivalent way:

    boolean helperResponse1 = helper(start + 1, nums, sum1 + nums[start], sum2);
    
    if (helperResponse1 == true)
        return true;
    else {
        boolean helperResponse2 = helper(start + 1, nums, sum1, sum2 + nums[start]);
        if (helperResponse2 == true)
            return true;
        else
            return false;
    }
    

    I put in a lot of unnecessary stuff for the sake of clarity.

提交回复
热议问题