1. 程式人生 > 其它 >【Codewars】<4kyu>Sum Strings as Numbers

【Codewars】<4kyu>Sum Strings as Numbers

技術標籤:Codewars演算法字串jsjavascript前端

題目

<4kyu>Sum Strings as Numbers

Given the string representations of two integers, return the string representation of the sum of those integers.
A string representation of an integer will contain no characters besides the ten numerals “0” to “9”.


給定兩個整數的字串表示形式,返回這些整數之和的字串表示形式。


(注:這兩個字串將不包含除“0”到“9”之外的任何字元。)

例子

sumStrings('1','2') // => '3'
sumStrings('','5') // => '5'
sumStrings('001','5') // => '6'
sumStrings('50095301248058391139327916261','81055900096023504197206408605') // => '131151201344081895336534324866'

題解一

// 題解一:
function sumStrings(a,b) {
    var result = '';
    var remainder =
0; if(a.length < b.length) { var c = a; a = b; b = c; } for(let i=1;i<=a.length;i++){ // 從最右邊開始,將兩個數求和,並加上上一次的餘數,首次餘數為0 var sum = (a.length-(i-1)>0 ? parseInt(a.substr(a.length-i,1)) : 0) + (b.length-(i-1)>0 ? parseInt(b.substr(b.length-i,1)
) : 0) + remainder; // 求和後去取餘,就是該位要保留的數字 result = sum%10 + result // 計算餘數 remainder = parseInt(sum/10) // 如果到了最左邊,即a的第一位,餘數還大於0,則直接加上餘數 if(remainder > 0 && i == a.length) result = remainder + result; } return result.replace(/\b(0+)/gi,""); // 去除字串前面的0 }

題解二(Best Practices)

// 題解二:
function sumStrings(a, b) {
    var res = '', c = 0;
    a = a.split('');
    b = b.split('');
    while (a.length || b.length || c) {
      c += ~~a.pop() + ~~b.pop();
      res = c % 10 + res;
      c = c > 9;
    }
    return res.replace(/^0+/, '');
}

小夥伴們有其它更好的解法,歡迎評論區提出交流~