广树
2024-11-22 20:09
@阿猫:原来如此😀
作者:广树时间:2018-07-23 12:08:54分类:JavaScript/jQuery/Vue
大整数相乘:
function multi(a,b){ var str1,str2,len1,len2,maxlen,result = []; str1 = a.split("").reverse(); str2 = b.split("").reverse(); len1 = str1.length; len2 = str2.length; for(var i = 0;i < len1;i++){ for(var j = 0;j < len2;j++){ result[i + j] = 0; } } for(var i = 0;i < len1;i++){ for(var j = 0;j < len2;j++){ result[i + j] += parseInt(str1[i]) * parseInt(str2[j]); } } var n = result.length; for(var k = 0;k < n;k++){ var temp = result[k]; if(temp >= 10) { result[k] = temp % 10; if(result[k + 1] === undefined){ result[k + 1] = 0; } result[k + 1] += Math.floor(temp / 10); } } return result.reverse().join(""); }
例子:
multi('5158','878361')
"4530586038"
字符串乘以n个0:
function StrPointAdd(str,s){ var resData = ''; if(str&&str!==''){ var strArr = str.split('.'); if(strArr.length===1){ resData = strArr[0]; for(var i=0;i<s;i++){ resData = resData + '0'; } }else if(strArr.length===2){ var l = strArr[1].length; var cha = l-s; if(cha>=0){ resData = strArr[1]; resData = resData.substring(0,l-cha)+'.'+resData.substring(l-cha); resData = strArr[0] + resData; }else{ resData = strArr[1]; for(var i=0;i<-cha;i++){ resData = resData + '0'; } resData = strArr[0] + resData; } } //去除多余的0 var res_ = resData; if(res_.indexOf('.')!==-1){ for(var i=0;i<res_.length;i++){ if(res_[res_.length-1-i]=='0'){ resData = res_.slice(0,res_.length-1-i); }else if(res_[res_.length-1-i]=='.'){ resData = res_.slice(0,res_.length-1-i); break }else{ break } } } res_ = resData; for(var i=0;i<res_.length;i++){ if(res_[i]=='0'){ resData = res_.slice(i+1); }else if(res_[i]=='.'){ resData = '0'+res_.slice(i); break; }else{ break; } } } return resData; }
例子:
StrPointAdd('123456789',5)
"12345678900000"
StrPointAdd('0.123456789',5)
"12345.6789"