Skip to content

Commit e324bdd

Browse files
committed
Add sum of digits squared
1 parent b75bf95 commit e324bdd

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

sum-of-square-digits/app.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
const numberInput = document.getElementById('numberInput');//number input
2+
const result = document.getElementById('result');//result display
3+
const option = document.getElementById('option');//option selection
4+
let mode = option.value;
5+
function calculateSumOfDigits() {//calculate sum of digits
6+
const number = parseFloat(numberInput.value);//get number value from input
7+
if (isNaN(number)) {//if entered number is not a number
8+
result.textContent = 'Please enter a valid number.';
9+
}
10+
const sum = calculateSum(number);//calculate sum of entered number
11+
result.textContent = sum;//display result
12+
}
13+
function calculateSumOfAllDigits(number) {//calculate sum of all digits
14+
const numberString = number.toString().split('e')[0].replaceAll('.', '').replaceAll('-', '');//remove non digit characters to avoid errors
15+
let sum = 0;
16+
for (let i = 0; i < numberString.length; i++) {
17+
const digit = parseInt(numberString[i], 10);
18+
sum += digit * digit;//square each digit
19+
}
20+
return sum;
21+
}
22+
23+
function calculateSumOfIntegerDigits(number) {//calculate sum of integer digits
24+
const integerString = parseInt(number, 10).toString().replaceAll('.', '').replaceAll('-', '');//remove non digit characters to avoid errors
25+
let sum = 0;
26+
for (let i = 0; i < integerString.length; i++) {
27+
const digit = parseInt(integerString[i], 10);
28+
sum += digit * digit;//square each digit
29+
}
30+
return sum;
31+
}
32+
33+
function calculateSum(number) {//calculate sum function
34+
if (mode === 'sumOfDigits') {//if mode is sum of digits
35+
return calculateSumOfAllDigits(number);//return sum of all digits
36+
} else if (mode === 'sumOfIntegerDigits') {//else if mode is sum of integer digits
37+
return calculateSumOfIntegerDigits(number);//return sum of integer digits
38+
}
39+
}

sum-of-square-digits/index.html

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<title>Sum of Digits Calculator</title>
5+
</head>
6+
<body>
7+
<h1>Sum of Digits Calculator</h1>
8+
<input type="number" id="numberInput">
9+
<select id="option"><!--mode to calculate sum-->
10+
<option value="sumOfDigits" selected>Sum of Digits</option>
11+
<option value="sumOfIntegerDigits">Sum of Integer Digits</option>
12+
</select>
13+
<button onclick="calculateSumOfDigits()">Calculate</button>
14+
Sum of Digits: <p id="result"><!--result display--></p>
15+
<script src="app.js"></script>
16+
</body>
17+
</html>

0 commit comments

Comments
 (0)