寫一個(gè)函數(shù)處理大數(shù)據(jù)的相加問題,所謂的大數(shù)據(jù)是指超出了整型,長整型之類的常規(guī)數(shù)據(jù)類型表示范圍的數(shù)據(jù)。實(shí)現(xiàn)語言不限。昨天在網(wǎng)上看到這道題,感覺很奇怪,難道還有什么算法能比原生的符號運(yùn)算更快?看到這個(gè)鏈接:http://niutuku.com/tech/javaScript/258837.shtml,我測試了一下,大數(shù)據(jù)函數(shù)就出錯(cuò),速度也明顯不行,請教這道題的思路是什么?(鏈接源代碼有筆誤,我修改了下,貼在下面)window.onload=function(){console.time("strNumAdd")varstrAdd=function(srcA,srcB){vari,temp,tempA,tempB,len,lenA,lenB,carry=0;varres=[],arrA=[],arrB=[],cloneArr=[];arrA=(srcA+"").split("");arrB=(srcB+"").split("");arrA.reverse();arrB.reverse();lenA=arrA.length;lenB=arrB.length;len=lenA>lenB?lenB:lenA;for(i=0;i9){res.push(temp-10);carry=1;}else{res.push(temp);carry=0;}}cloneArr=lenA>lenB?arrA:arrB;for(;i9){res.push(temp-10);carry=1;}else{res.push(temp);carry=0;}}return(res.reverse()).join('');};console.log(strAdd(23909080089709873508234,9834309800089325675433678))console.timeEnd("strNumAdd")console.time("normalAdd")console.log(23909080089709873508234,9834309800089325675433678)console.timeEnd("normalAdd")}
有道前端面試題:兩個(gè)很大數(shù)如何做加法運(yùn)算?
紅糖糍粑
2019-04-07 09:38:19