Finding closest sum of numbers to a given number

后端 未结 5 1720
我在风中等你
我在风中等你 2021-01-25 09:11

Say I have a list [1,2,3,4,5,6,7] and I would like to find the closest sum of numbers to a given number. Sorry for the crappy explanation but here\'s an example:

Say I h

5条回答
  •  攒了一身酷
    2021-01-25 09:48

     var data= [1, 2, 3,4,5,6,7];
      var closest = 14;
     for (var x = 0; x < data.length; x++) {
        for (var y = x+1; y < data.length; y++) {
                 if(data[x] + data[y] == closet){
                         alert(data[x].toString() + "  " + data[y].toString());
                    }
                }
           }
    

提交回复
热议问题