Skip to content

Commit

Permalink
170th Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Shyam-Chen committed Jul 20, 2024
1 parent 1de03c4 commit 8d6cb96
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
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);
});
});
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);
};

0 comments on commit 8d6cb96

Please sign in to comment.