From b4ef20d71666f5d2d9a6fa2af137a1012aed9a4f Mon Sep 17 00:00:00 2001 From: alan1001110 Date: Sat, 17 Aug 2019 05:40:54 -0700 Subject: [PATCH] replaced stub with solution to large sum (#36618) replaced stub with solution to large sum, explanation, links --- .../problem-13-large-sum/index.md | 32 +++++++++++++++++-- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/guide/english/certifications/coding-interview-prep/project-euler/problem-13-large-sum/index.md b/guide/english/certifications/coding-interview-prep/project-euler/problem-13-large-sum/index.md index 1dd8d595fa7..0b3444a2d63 100644 --- a/guide/english/certifications/coding-interview-prep/project-euler/problem-13-large-sum/index.md +++ b/guide/english/certifications/coding-interview-prep/project-euler/problem-13-large-sum/index.md @@ -1,10 +1,36 @@ --- title: Large sum --- + ## Problem 13: Large sum +Challenge: Work out the first ten digits of the sum of one-hundred 50-digit numbers. -This is a stub. Help our community expand it. +## Spoiler Alert! -This quick style guide will help ensure your pull request gets accepted. +## One Solution: +``` +function largeSum(arr) { + let sum = arr.reduce((acc, item) => acc + Number(item), 0); // 8.348422521139211e+49 + let str = sum.toString().split('e')[0]; // '8.348422521139211' + return 1e+9 * str.slice(0,11); // 8348422521 +} - +const testNums = [ + '37107287533902102798797998220837590246510135740250', + '46376937677490009712648124896970078050417018260538' +]; + +largeSum(testNums); +``` +### Code Explanation: + +* The function receives an array of strings +* The first line converts the strings to numbers and adds them +* The second line converts the large sum to a string with toString, then gets everything to the left of 'e' using String.split(). +* The third line multiplies 1,000,000,000 by the first 11 characters to implicitly coerce the string to a 10 digit number +* Note: One regular expression could accomplish the same task as the second and third lines together + +### Resources + +* Array.reduce() +* String.split()