11.總數字作為數字Sum Strings as Numbers
總的來說這是一個將字符串轉化為數字進行計算再轉化為字符串的計算,醉生與死;
Given the string representations of two integers, return the string representation of the sum of those integers.
For example:
sumStrings(‘1‘,‘2‘) // => ‘3‘
A string representation of an integer will contain no characters besides the ten numerals "0" to "9".
function sumStrings(a,b) {
var arr=[];
var a=a.split("").reverse();
var b=b.split("").reverse();
if(a.length<b.length){
var c=a;
a=b;
b=c;
}
for(var i=0;i<a.length;i++){
if(i<b.length){
arr[i]=parseInt(a[i])+parseInt(b[i])
}else{
arr[i]=parseInt(a[i])
}
}
arr.reverse();
for(var i=arr.length-1;i>0;i--){
if(arr[i]>=10){
arr[i]=arr[i]%10;
arr[i-1]=arr[i-1]+1;
}
console.log(arr[i])
}
for(var i=0;i<arr.length;i++){
if(arr[i]==0){
arr.splice(i,1);
}else{
break;
}
}
return arr.join("");
}
測試使用的數字:
a:123 b:456 a:8797 b:45 a:800 b:9567 a:99 b:1 a:00103 b:08567 a: b:5 a:712569312664357328695151392 b:8100824045303269669937 a:50095301248058391139327916261 b:8105590009602350419720640860511.總數字作為數字Sum Strings as Numbers