Similar Problems
Similar Problems not available
Difference Between Element Sum And Digit Sum Of An Array - Leetcode Solution
Companies:
LeetCode: Difference Between Element Sum And Digit Sum Of An Array Leetcode Solution
Difficulty: Easy
Problem Statement:
Given an integer array nums, return the difference between the sum of all elements and the sum of the digits of each element.
Example:
Input: nums = [12, 15]
Output: 21
Explanation:
For the element 12, the sum of the digits = 1+2 = 3, and the difference between 12 and 3 = 9.
For the element 15, the sum of the digits = 1+5 = 6, and the difference between 15 and 6 = 9.
So, the total difference is 9+9=18.
Solution:
The problem requires us to find the difference between the sum of all the elements in the array and the sum of each element's digits.
We can loop through the given array, sum up all the elements in the array, and calculate the sum of digits for each element of the array using the modulo %
operator and integer division //
.
We can define a function named digit_sum
that takes an integer as input and returns the sum of its digits. We can calculate the digit sum as follows:
def digit_sum(n:int) -> int: s = 0 while n > 0: s += n % 10 n //= 10 return s
Now we can loop through the array and get the sum of all the digits in each element of the array. We can add these sums to a variable named digits_sum
. We can also compute the sum of all elements of the array nums
and store it in a variable named elements_sum
.
digits_sum = 0 elements_sum = sum(nums) for num in nums: digits_sum += digit_sum(num)
Finally, we can calculate the difference between the sum of all elements and the sum of each element's digits as:
result = elements_sum - digits_sum
We can return this result
as a solution to the problem.
Complete Solution:
The complete solution in Python 3.x can be given as follows:
def digit_sum(n:int) -> int: s = 0 while n > 0: s += n % 10 n //= 10 return s
class Solution: def subtractProductAndSum(self, nums: List[int]) -> int: digits_sum = 0 elements_sum = sum(nums) for num in nums: digits_sum += digit_sum(num)
result = elements_sum - digits_sum
return result
Time Complexity: O(n), where n is the length of the given array.
Space Complexity: O(1), as no extra space is used.
Difference Between Element Sum And Digit Sum Of An Array Solution Code
1