javascript - Codefights: Correct solution but system does not accept it -


experienced codefighters, have started using codefight website learn javascript. have solved task system not accept it. task sum integers (inidividual digit) in number. example sumdigit(111) = 3. wrong code? please me.

code

function digitsum(n) {     var emptyarray = [];     var total = 0;     var number = n.tostring();     var res = number.split("");     (var i=0; i<res.length; i++) {         var numberind = number(res[i]);         emptyarray.push(numberind);      }      var finalsum = emptyarray.reduce(add,total);      function add(a,b) {          return + b;      }      console.log(finalsum);     //console.log(emptyarray);     //console.log(res); } 

here's faster trick summing individual digits of number using arithmetic:

var digitsum = function(n) {   var sum = 0;   while (n > 0) {     sum += n % 10;     n = math.floor(n / 10);   }   return sum; }; 

n % 10 remainder when divide n 10. effectively, retrieves ones-digit of number. math.floor(n / 10) integer division of n 10. can think of chopping off ones-digit of number. means code adds ones digit sum, chops off ones digit (moving tens digit down ones-digit was) , repeats process until number equal 0 (i.e. there no digits left).

the reason why more efficient method doesn't require converting integer string, potentially costly operation. since codefights test of algorithmic ability, looking more algorithmic answer, 1 explained above.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -