猿问

javaScript中给定一个动态的数字,怎么知道这个数字是由数组中哪几个数字相加而成的

  1. 比如存在一个数组[1,2,4,8,16,32];然后给定一个数字,这个数字是由数组中某些数字相加得到的,问题是怎么找到是由数组中哪几个数字相加而成的?


慕容708150
浏览 734回答 1
1回答

喵喵时光机

最笨的方法可以用两层for循环计算const arr = [1,2,4,8,16,32];function addResult(arr,value){&nbsp; &nbsp; let key = [];&nbsp; &nbsp; for(let i = 0; i < arr.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; let d = arr[i];&nbsp; &nbsp; &nbsp; &nbsp; for( let j = 0; j < arr.length;j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let jd = arr[j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if( d + jd === value ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key = [i,j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if( key.length > 0 ) break;&nbsp; &nbsp; }&nbsp; &nbsp; return key;}addResult(arr,4)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答