Input: nums =[1,15,6,3]Output: 9Explanation:
The element sum of nums is1+15+6+3=25.The digit sum of nums is1+1+5+6+3=16.The absolute difference between the element sum and digit sum is|25-16|=9.
Input: nums =[1,2,3,4]Output: 0Explanation:
The element sum of nums is1+2+3+4=10.The digit sum of nums is1+2+3+4=10.The absolute difference between the element sum and digit sum is|10-10|=0.
The element sum is simply the sum of all numbers in the array. The digit sum is the sum of all digits of all numbers. The answer is the absolute difference between these two sums.
classSolution {
public:int differenceOfSum(vector<int>& nums) {
int elem_sum =0, digit_sum =0;
for (int x : nums) {
elem_sum += x;
int y = x;
while (y) {
digit_sum += y %10;
y /=10;
}
}
returnabs(elem_sum - digit_sum);
}
};
classSolution {
publicintdifferenceOfSum(int[] nums) {
int elemSum = 0, digitSum = 0;
for (int x : nums) {
elemSum += x;
int y = x;
while (y > 0) {
digitSum += y % 10;
y /= 10;
}
}
return Math.abs(elemSum - digitSum);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
fundifferenceOfSum(nums: IntArray): Int {
var elemSum = 0var digitSum = 0for (x in nums) {
elemSum += x
var y = x
while (y > 0) {
digitSum += y % 10 y /=10 }
}
return kotlin.math.abs(elemSum - digitSum)
}
}
1
2
3
4
5
classSolution:
defdifferenceOfSum(self, nums: list[int]) -> int:
elem_sum = sum(nums)
digit_sum = sum(int(d) for x in nums for d in str(x))
return abs(elem_sum - digit_sum)