function - A while loop to add the digits of a multi-digit number together? (Javascript) -
i need add digits of number (e.g. 21 2+1) number reduced 1 digit (3). figured out how part.
however,
1) may need call function more once on same variable (e.g. 99 9+9 = 18, still >= 10) and
2) need exclude numbers 11 , 22 function's ambit.
where going wrong below?
var x = 123; var y = 456; var z = 789; var numbermagic = function (num) { var proc = num.tostring().split(""); var total = 0; (var i=0; i<proc.length; i++) { total += +proc[i]; }; }; while(x > 9 && x != 11 && x != 22) { numbermagic(x); }; } else { xresult = x; }; console.log(xresult); //repeat while loop y , z
here problems code
var x = 123; var y = 456; var z = 789; var numbermagic = function (num) { var proc = num.tostring().split(""); var total = 0; (var i=0; i<proc.length; i++) { total += +proc[i]; // indentation want awry }; // don't need ; - not show stopper // you're not returning anything!!!! }; while(x > 9 && x != 11 && x != 22) { numbermagic(x); }; // ; not needed // because x never changes, above while loop go on forever } else { // else has no if xresult = x; // if code right, x remains unchanged }; console.log(xresult);
hope helps in way
now - here's solution works
var x = 123; var y = 456; var z = 789; var numbermagic = function (num) { while (num > 9) { if (num == 11 || num == 22) { return num; } var proc = num.tostring().split(""); num = proc.reduce(function(previousint, thisvaluestring) { return previousint + parseint(thisvaluestring); }, 0); } return num; } console.log(numbermagic(x)); console.log(numbermagic(y)); console.log(numbermagic(z));
Comments
Post a Comment