-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1de03c4
commit 8d6cb96
Showing
2 changed files
with
27 additions
and
0 deletions.
There are no files selected for viewing
8 changes: 8 additions & 0 deletions
8
...24/2535. Difference Between Element Sum and Digit Sum of an Array/differenceOfSum.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import { differenceOfSum } from './differenceOfSum'; | ||
|
||
describe('2535. Difference Between Element Sum and Digit Sum of an Array', () => { | ||
test('differenceOfSum', () => { | ||
expect(differenceOfSum([1, 15, 6, 3])).toBe(9); | ||
expect(differenceOfSum([1, 2, 3, 4])).toBe(0); | ||
}); | ||
}); |
19 changes: 19 additions & 0 deletions
19
...page-24/2535. Difference Between Element Sum and Digit Sum of an Array/differenceOfSum.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
type DifferenceOfSum = (nums: number[]) => number; | ||
|
||
/** | ||
* Accepted | ||
*/ | ||
export const differenceOfSum: DifferenceOfSum = (nums) => { | ||
// Calculate the element sum | ||
const elementSum = nums.reduce((sum, num) => sum + num, 0); | ||
|
||
// Calculate the digit sum | ||
const digitSum = nums.reduce((sum, num) => { | ||
const digits = String(num).split(''); | ||
const digitSumForNum = digits.reduce((digitSum, digit) => digitSum + Number(digit), 0); | ||
return sum + digitSumForNum; | ||
}, 0); | ||
|
||
// Return the absolute difference | ||
return Math.abs(elementSum - digitSum); | ||
}; |