This is a DP problem. You can solve this problem with Digit DP. If you don't know about Digit DP, see This