Difference Between Element Sum and Digit Sum of an Array - Modulo 10 [JS]
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 nums
, m = 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
Post a Comment