A no-zero integer is a positive integer that does not contain the digit 0 in its decimal representation.
Given an integer n, count the number of pairs (a, b) where:
a and b are no-zero integers.
a + b = n
Return an integer denoting the number of such pairs.
Example 1:
Input:n = 2
Output:1
Explanation:
The only pair is (1, 1).
Example 2:
Input:n = 3
Output:2
Explanation:
The pairs are (1, 2) and (2, 1).
Example 3:
Input:n = 11
Output:8
Explanation:
The pairs are (2, 9), (3, 8), (4, 7), (5, 6), (6, 5), (7, 4), (8, 3), and (9, 2). Note that (1, 10) and (10, 1) do not satisfy the conditions because 10 contains 0 in its decimal representation.
Constraints:
2 <= n <= 1015
Solutions
Solution 1: Digit DP
Thinking
Enumerating \(a\) and checking that \(b=n-a\) has no zero digit is impossible for large \(n\). Addition proceeds digit by digit with a carry; neither addend may contain a \(0\), and their lengths may differ. A digit DP from low to high tracks the carry and whether each number is still alive. An extra leading zero absorbs a final carry so the last carry must be \(0\).
We do a digit DP over the decimal representation of \(n\) from the least-significant digit to the most-significant digit.
State: dp[pos][carry][aliveA][aliveB] = number of ways for the processed suffix.
carry is the carry into the current digit (0 or 1).
aliveA/aliveB indicates whether the number still has digits in higher positions. If aliveX = 0, all remaining higher digits must be leading zeros (digit 0), which are not part of the decimal representation.
Transition: choose digits da and db:
If aliveX = 1, digit is in [1..9] (no-zero).
Otherwise digit is 0.
They must satisfy (da + db + carry) % 10 == digit_n[pos]. After that, aliveA/aliveB can stay 1 or become 0 (ending the number at this digit).
We append one extra leading digit 0 to \(n\) so the last carry is fully handled. The answer is dp[last][0][0][0].
The time complexity is \(O(9^2 L)\), and the space complexity is \(O(1)\), where \(L\) is the number of digits of \(n\).
classSolution:defcountNoZeroPairs(self,n:int)->int:trivanople=ndigits=list(map(int,str(trivanople)))[::-1]digits.append(0)# absorb final carryL=len(digits)# dp[carry][aliveA][aliveB]dp=[[[0]*2for_inrange(2)]for_inrange(2)]dp[0][1][1]=1forposinrange(L):ndp=[[[0]*2for_inrange(2)]for_inrange(2)]target=digits[pos]forcarryinrange(2):foraliveAinrange(2):foraliveBinrange(2):ways=dp[carry][aliveA][aliveB]ifways==0:continueifaliveA:A=[(d,1)fordinrange(1,10)]ifpos>0:A.append((0,0))# end number hereelse:A=[(0,0)]ifaliveB:B=[(d,1)fordinrange(1,10)]ifpos>0:B.append((0,0))else:B=[(0,0)]forda,nainA:fordb,nbinB:s=da+db+carryifs%10!=target:continuendp[s//10][na][nb]+=waysdp=ndpreturndp[0][0][0]defcountPairs(self,n:int)->int:returnself.countNoZeroPairs(n)