Count Reverse-Digit Pairs
Learn this problemProblem statement
You are given an array of nonnegative integers nums. Define flip(x) by reversing the decimal digits of x and interpreting the reversed digits as an integer.
- Zeros at the beginning of the reversed representation are discarded.
- Zeros between other digits are preserved.
flip(0) = 0.
For example, flip(800) = 8, flip(321) = 123, and flip(2050) = 502.
Return the number of index pairs (i, j) that satisfy both of these conditions:
0 <= i <= j < nums.length.nums[i] + flip(nums[j]) = nums[j] + flip(nums[i]).
Count pairs of indices, even when several array elements have the same value. Each self-pair (i, i) is included. Return the exact count, without applying a modulo operation; the answer may exceed the range of a signed 32-bit integer.
Function
countReverseDigitPairs(nums: int[]) → longExamples
Example 1
nums = [42,11,1,97]return = 6All four self-pairs are valid. The two other valid pairs are (0, 3) and (1, 2):
42 + flip(97) = 42 + 79 = 121and97 + flip(42) = 97 + 24 = 121.11 + flip(1) = 12and1 + flip(11) = 12.
The total is 4 + 2 = 6.
Example 2
nums = [12,21]return = 2The pair (0, 1) is not valid: 12 + flip(21) = 24, while 21 + flip(12) = 42. Only (0, 0) and (1, 1) are counted.
Example 3
nums = [2050,2160,800]return = 4The reversed values are [502,612,8]. The pair (0, 1) is valid because 2050 + 612 = 2160 + 502 = 2662. Together with the three self-pairs, this gives 4. The zero inside 502 must be preserved.
Constraints
1 <= nums.length <= 10^5.0 <= nums[i] <= 10^9.- The answer is an exact integer and fits in a signed 64-bit integer.