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!
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).
i use it :)
var result = eval('123456'.replace(/(\d)(?=\d)/g, '$1+'));
alert(result); // 21
without eval
var result = '123456'.split('').reduce(function(a,b){ return +a+ +b; });
alert(result); // 21
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With