repl.it
@cmclau01/

sumOfDigits exercise

JavaScript

function to add together the individual digits of a number parameter.

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/*
Sum Of Digits- Exercise Link

Create the function sumOfDigits that adds individual digits of a number and return the sum.


**Example:**

- INPUT: `sumOfDigits(414);`
4+1+4
- Return Value: `9`

- INPUT: `sumOfDigits(2913);`
- Return Value: `15`




TIP:

You may need to use the following methods or operators in your solution, reference the workshop page for additional information.

*/
/* My original code, though I negelected to convert num to a string:
function sumOfDigits (num) {
  debugger;
  let numString = num.toString();
  let sum = 0;
  for (i = 0; i < numString.length; i++) {
    sum += +numString[i];
    // this tells sum to increment by adding each index of the string.
  }
  return sum;
}
sumOfDigits(987);*/
function sumOfDigits(int) {
  debugger;
  var sum = 0;
  // defines the variable sum to store the incremented value;
  while (int > 0) {
    //since we are adding numbers, we want the value of int to increment as long as it has value.
    sum += int % 10;
    //the sum will be incremented by int mod 10. the result of this will be that the last digit in each iteration will be added to the variable sum. e.g. 987 % 10 after the first iteration will be 7, then 15 (8 + 7), and finally, 24 (7 + 8 + 9),
    int = Math.floor(int/10);  
    //we then must redefine int at the end of the iteration in order to decrement the digit. e.g. with 987, 987 % 10 will be 7, then redefine int as 98.7 and use the Math.floor method to round down, which reassigns the value 98 to int. On the next iteration this will become 9, and finally 0.
  }
  return sum;
}
sumOfDigits(987);






































































/* TEST CASES */

// console.log(sumOfDigits(414));
// => logs 9 since (4+1+4) === 9;

// console.log(sumOfDigits(2193));
// => logs 15 since (3+9+1+2) === 15;




Native Browser JavaScript
?