All possibilities to put +, - or nothing between numbers to get sum equal to 100

后端 未结 2 1784
再見小時候
再見小時候 2020-12-20 09:43

I have to built a function which would list the all possibilities to put +, - or nothing between the numbers ranging from 1 to 9 and print it result.

For example: 1

相关标签:
2条回答
  • 2020-12-20 10:38
    def hun(exp, i):
            if (i<=9):
                    for mark in ("+", "-", ""):
                            hun(exp + mark + str(i), i+1)
            elif eval(exp) == 100:
                    print(exp + " = 100")
    hun("1",2)
    
    0 讨论(0)
  • 2020-12-20 10:42

    You can do it by recursive - Use the following code:

    <?php
    
    function addNum($baseStr, $nextNum)
    {
     if ($nextNum == 10)
         return array($baseStr);
     $arr1 = addNum($baseStr. '+' . $nextNum, $nextNum+1);
     $arr2 = addNum($baseStr. '-' . $nextNum, $nextNum+1);
     $arr3 = addNum($baseStr. '' . $nextNum, $nextNum+1);
        return array_merge($arr1, $arr2, $arr3);
    }
    
    $permutation = addNum('1', 2);
    foreach ($permutation as $perm)
    {
     $res = eval("return $perm;");
     echo $perm . '=' . $res . "\n";
    }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题