Difference Between Element Sum and Digit Sum of an Array - Modulo 10 [JS]

Description 

Solution: Modulo 10

To get the digit sum of a number, use modulo 10 to get the last digit.
Divide the number by 10 and round it down to remove the last digit.

n = length of numsm = max(nums[i])
Time Complexity: O(n log(m)) 74ms
Space Complexity: O(1) 44.2MB

var differenceOfSum = function(nums) {
  let elementSum = nums.reduce((sum, num) => sum + num, 0);
  let digitSum = nums.reduce((sum, num) => sum + getDigitSum(num), 0);
  return Math.abs(elementSum - digitSum);
};

function getDigitSum(num) {
  let sum = 0;
  while (num > 0) {
    let digit = num % 10;
    sum += digit;
    num = Math.floor(num / 10);
  }
  return sum;
}

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]