2016-01-24 47 views
0
// Produce the element with largest sum of each integer in the string. 
var phoneList1 = ["111-111-1113", "111-111-1113", "111-111-1111", "111-111-1112"]; 

for (var i = 0; i < phoneList1.length; i++) {   // Iterating through the array 
    phoneList1[i] = phoneList1[i].replace(/-/g, ''); // Removing the dashes (-) 
    phoneList1[i] = parseInt(phoneList1[i], 10);  // Converting to integers 
} 

這就是我所得到的。如何生成字符串中每個整數的總和最大的元素?

給定一組電話號碼,我怎樣才能找到列表中的項目,當字符串中的每個數字加在一起時,是列表中所有項目中最大的。

例子:"111-111-1111" = 10

+3

您能否澄清此方法的功能?當你解析電話號碼時,你的意思是「連續整數最大的元素」?您的樣本輸入的預期輸出是什麼? – Nate

+0

你想要的輸出是什麼? ** 111-111-1113 **或** 1111111113 **或其他東西? – mmuzahid

+0

按** - **分割電話號碼,並將數組中的每個元素轉換爲數字並進行總和。如果總和大於先前的值,則將其存儲爲下一次迭代的結果。 – mmuzahid

回答

0

你打開你的瀏覽器的控制檯,並粘貼如下代碼:

var phoneList1 = ["111-111-1113", "111-111-1113", "111-111-1111", "111-111-1112"]; 
 

 
//this function returns the largest sum 
 
function mainWithTrack(phoneBook){ 
 
    //number is a string with integers and dashes(or other chars) 
 
    function convertNumberToInt(number){ 
 
    var numberDigits = number.split(''); 
 
    var sum = 0; 
 
    numberDigits.forEach(function(number){ 
 
     if (parseInt(number)){ 
 
     sum += parseInt(number); 
 
     } 
 
    }); 
 
    return sum; 
 
    } 
 
    var convertedPhoneBook = phoneBook.map(function(phoneNumber, index){ 
 
     return { number: convertNumberToInt(phoneNumber), index: index }; 
 
    }); 
 
    function compareNumbers(a, b) { 
 
    return a.number - b.number; 
 
    } 
 
    return convertedPhoneBook.sort(compareNumbers)[phoneBook.length-1]; 
 
} 
 
//now call it 
 
var largest = mainWithTrack(phoneList1); 
 
console.log("Largest sum is ", largest.number, " at index ", largest.index, " in phoneList1: ", phoneList1[largest.index]);

0

下面適用於您的情況:

var pn = [ 
 
    0, 
 
    "more invalid numbers", 
 
    "111-111-111", 
 
    "111-111-112", 
 
    "111-111-115", 
 
    "111-711-111", 
 
    "111-111-113", 
 
    1, 
 
    "invalid" 
 
]; 
 

 
// String summing function 
 
function sumPN(s) { 
 
    if (typeof(s) !== "string") 
 
    return 0; 
 
    return s.split("").reduce(function(r, n) { 
 
    // All non-digits are set to 0 
 
    r = parseInt(r); 
 
    n = parseInt(n); 
 
    if (isNaN(r)) 
 
     r = 0; 
 
    if (isNaN(n)) 
 
     n = 0; 
 
    return r+n; 
 
    }); 
 
} 
 

 
function getLarge(a) { 
 
    var sum = 0; 
 
    return a[a.reduce(function(large, cur, idx) { 
 
    // convert first element 
 
    if (idx === 1) { 
 
     sum = sumPN(large); 
 
     large = 0; 
 
    }; 
 

 
    // parse all the rest, compare, set new index and sum where necessary 
 
    curSum = sumPN(cur); 
 
    console.log(curSum, cur); 
 
    if (curSum > sum) { 
 
     sum = curSum; 
 
     return idx; 
 
    } 
 
    return large 
 
    })]; 
 
} 
 
document.write(getLarge(pn));

相關問題