Untitled

 avatar
unknown
plain_text
a year ago
1.1 kB
8
Indexable
/*
This code takes an array of integers where each integer has the same number of digits. It calculates the sum of differences between corresponding digits of all pairs of integers in the array. For example, if we have the numbers 123 and 456, the differences would be 1-4, 2-5, and 3-6, resulting in a total sum of differences.
*/
class Solution {
   public  static long sumDigitDifferences(int[] nums) {
        int n = nums.length;
        if (n < 2) return 0;
        String[] str = new String[n];
        int digit = String.valueOf(nums[0]).length();
        for (int i = 0; i < n; i++) {
            str[i] = String.valueOf(nums[i]);
        }
        long answer = 0;
        for (int pos = 0; pos < digit; pos++) {
            int[] count = new int[10];
            for (String string : str) {
                int temp = string.charAt(pos) - '0';
                count[temp]++;
            }
            for (int i = 0; i < 10; i++) {
                for (int j = i + 1; j < 10; j++) {
                    answer += (long) count[i] * count[j];
                }
            }
        }
        return answer ;
    }
}
Editor is loading...
Leave a Comment