digitSumDifference
with Carmen Salas • 2024/11/04
Code Challenge
Using methods...
/*
## PEDAC
**Problem**
Parse a number into individual digits and output the difference between the sum of all evens and all odds.
Number -> Number indicating the difference (as described above)
**Examples/Edge Cases:**
2134 -> 6 (evens) - 4 (odds) == 2
**Data Structure**
- Number
- String
- Array
**Algorithm**
1. Convert number into string.
2. Split string into array.
3. Convert each item into a number.
4. Look at each number in the array: if even, add value to sum, else subtract value from sum.
*/
function solution(n) {
// method approach
return [...String(n)] // step 1 and 2
.reduce((sum, val) => // step 3 and 4
// loose equality for type conversion
(val%2 == 0) ? sum+Number(val) : sum-Number(val), 0);
}
Simple no-method approach
/*
## PEDAC
**Problem**
- Given a Number, look at each digit individually and sum all the evens and all the odds. The result will be the difference between sumEvens-sumOdds.
- We can skip the need for two sums because we notice that:
all evens are additive, while
all odds are subtractive.
- Meaning, we can just add all evens and subtract all odds to get the sum.
**Examples/Edge Cases:**
input: 1234 => 1 , 2 , 3 , 4 => sum(2,4) - sum(1,3) => 2
^ ^ ^ ^ ^ ^ ^
look at each evens odds result
**Data Structures**
- Number
- While loops
- Conditional (ternary in this case)
**Algorithm**
While n > 0, for each iteration:
- do n%10 (this takes the value of the `ones` place)
- if n%10 is even, ADD it to sum
odd, SUBTRACT it from sum
- do n // 10 (integer division)
Return the resulting sum.
Walkthrough for input = 1234
----------------------------
While (n > 0) loop:
1st loop: sum = 0
1234 % 10 => 4
4 is even, sum += 4
1234 / 10 => Math.floor(123.4) => 123
2nd loop: sum = 4
123 % 10 => 3
3 is odd, sum -= 3
123 / 10 => Math.floor(12.3) => 12
3rd loop: sum = 1
12 % 10 => 2
2 is odd, sum += 2
12 / 10 => Math.floor(1.2) => 1
4th loop: sum = 3
1 % 10 => 1
1 is odd, sum -= 1
1 / 10 => Math.floor(0.1) => 0
Exit loop with sum = 2.
*/
function solution(n) {
let sum = 0; // initialize the sum
while (n > 0) {
const rem = n%10; // remainder by 10 is effectively the number in the `ones` place
(rem%2 === 0) ? sum += rem : sum -= rem; // add if even, subtract if odd
n = Math.floor(n/10); // integer division, to remove the `ones` number we just processed
}
return sum; // return the sum
}
Last updated