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 10’s complement.
Input: N = 10, str1 = “3434243434”, M = 14, str2 = “22324365765767”
Input: N = 20, str1 = “12345334233242431433”, M = 20, str2 = “12345334233242431432”
Approach: 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 + (10’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 10’s compliment of str2.
- Now, add 10’s compliment of str2 to str1.
- If any carry is generated, then drop the carry.
- 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.