Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  16] [ 2]  / answers: 1 / hits: 27863  / 13 Years ago, sat, february 4, 2012, 12:00:00

I saw a bunch of other posts on this topic but none in javascript. here is my code.



var theNumber = function digitAdd (base, exponent) {
var number = 1;
for (i=0; i < exponent; i++) {
var number = base * number;
}
return number
}


function find(theNumber) {
var sum=0;
parseInt(theNumber);
while(theNumber>0)
{
sum=sum+theNumber%10;
theNumber=Math.floor(theNumber/10);
}
document.writeln(Sum of digits +sum);
}

find(theNumber (2, 50));


I am getting the correct answer, I just don't fully understand the 2nd function, namely the while statement. Any help would be greatly appreciated. Thanks!


More From » parsing

 Answers
4

The second function uses the modulo operator to extract the last digit:



  1236 % 10
= 1236 - 10 * floor(1236 / 10)
= 1236 - 1230
= 6


When the last digit is extracted, it is subtracted from the number:



  1236 - 6
= 1230


And the number is divided by 10:



  1230 / 10
= 123


Each time this loop repeats, the last digit is chopped off and added to the sum.



The modulo operator returns the single digit if the left hand side is smaller than the right (which will happen for any 1-digit number), which is when the loop breaks:



  1 % 10
= 1


This is how the leading digit gets added to the total.






A less numeric alternative would be this:



function sumDigits(number) {
var str = number.toString();
var sum = 0;

for (var i = 0; i < str.length; i++) {
sum += parseInt(str.charAt(i), 10);
}

return sum;
}


It does literally what you are trying to do, which is iterate over the digits of the number (by converting it to a string).


[#87650] Thursday, February 2, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karyme

Total Points: 545
Total Questions: 102
Total Answers: 120

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
;