typedeflonglong ll; classSolution { public: ll sumDigitDifferences(vector<int>& nums){ ll ans = 0; do { ll times[10] = {0}; for (int& t : nums) { times[t % 10]++; t /= 10; } for (int i = 0; i < 10; i++) { ans += times[i] * (nums.size() - times[i]); } } while (nums[0]); return ans / 2; } };
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package main
funcsumDigitDifferences(nums []int)int64 { ans := int64(0) for nums[0] > 0 { times := make([]int, 10) for i, n := range nums { times[n % 10]++ nums[i] /= 10 } for i := 0; i < 10; i++ { ans += int64(times[i] * (len(nums) - times[i])) } } return ans / 2 }
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { publiclongsumDigitDifferences(int[] nums) { longans=0; while (nums[0] > 0) { long[] times = newlong[10]; for (inti=0; i < nums.length; i++) { times[nums[i] % 10]++; nums[i] /= 10; } for (inti=0; i < 10; i++) { ans += times[i] * (nums.length - times[i]); } } return ans / 2; } }
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
from typing importList
classSolution: defsumDigitDifferences(self, nums: List[int]) -> int: ans = 0 n = max(nums) while n: # while nums[0]的话可能会有[0, 1]的情况 # 后续更新:忽然发现题目限定是正数,有点过考虑了 n //= 10 times = [0] * 10 for th, x inenumerate(nums): times[x % 10] += 1 nums[th] //= 10 for i inrange(10): ans += times[i] * (len(nums) - times[i]) return ans // 2