[Javascript] How to sum of all its digits for a number


Given a number x, find sum of digits in that number.
Examples:

1. Input n = 8
Output - Sum of digits in number is 8

2. Input n = 1234
Output - Sum of digits in number is 10

3. Input n = - 8
Output - Sum of digits in number is -8

4. Input n = -1234
Output - Sum of digits in number is 8

Step 1: we have to create a demo.html
<!DOCTYPE html>
<html>
<body>
<h2>The sum of all digits</h2>
<p>Given a number, the program will return the sum of all its digits (negative digits will count as negative)</p>
<input type="text" value="Input number" id="demo">
<input type="button" id="btnSum" onclick="mySumFunction()" value="Sum">
<p id="result"></p>
<input type="text" value="Input number" id="demo1">
<input type="button" id="btnSum" onclick="mySumFunction1()" value="Sum1">
<p id="result1"></p>
<script>
function mySumFunction()
{
var num = parseInt(document.getElementById("demo").value);
var sum = 0, remainder = 0;
var offset = false;
if (num < 0)
{
offset = true;
num = num * (-1);
}
while(num)
{
remainder = num % 10;
sum += remainder;
num = (num - remainder) / 10;
}
if (offset)
{
sum = sum - (2 * remainder);
}
document.getElementById("result").innerHTML = sum;
}
function mySumFunction1()
{
var textType = Node.textContent ? 'textContent' : 'innerText';
var num = parseInt(document.getElementById("demo1").value);
var sum = 0, remainder = 0;
var offset = false;
if (num < 0)
{
offset = true;
num = num * (-1);
}
while(num)
{
remainder = num % 10;
sum += remainder;
num = (num - remainder) / 10;
}
if (offset)
{
sum = sum - (2 * remainder);
}
result1[textType] = sum;
}
</script>
</body>
</html>
view raw gistfile1.txt hosted with ❤ by GitHub


Step 2: we write the function in javascript to sum of all digits in a number. With 2 ways to declare the function.

The first one: using var num = parseInt(document.getElementById("demo").value); when everything is done, we got the sum. We will use document.getElementById("result").innerHTML = sum to show on web browser.

The second one: using var textType = Node.textContent ? 'textContent' : 'innerText'; Is is the textContent or innerText? You also do something like the first one, but when you get the value for <p> tag. Just using like this result1[textType] = sum;

Let's do it now






[Javascript] How to sum of all its digits for a number

No comments:

Post a Comment