Given two strings str1 and str2 of given lengths N and M respectively, each representing a large number, the task is to subtract one from the other using 9’s complement.
Input: N = 17, str1 = “12345678987654321”, M = 11, str2 = “22324324343”
Input: N = 20, Str1 = “12345334233242431433”, M = 20, Str2 = “12345334233242431432”
The basic idea is similar to Subtraction of two numbers using 2’s complement.
Subtraction of given strings can be written as
Str1 – Str2 = Str1 + (- Str2) = Str1 + (9’s complement of Str2)
Follow the steps below to solve the problem:
- Compare the lengths of the two strings and store the smaller of the two in str2.
- Calculate 9’s compliment of str2.
- Now, add 9’s compliment of str2 to str1.
- If any carry is generated, insert at the beginning of str1.
- If no carry is generated, then the compliment of str1 is the final answer.
Below is the implementation of the above approach:
Time Complexity: O(max(N, M))
Auxiliary Space: O(max(N, M))
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.