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 DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Subtraction of two large numbers using 10's compliment
- Subtraction of two numbers using 2's Complement
- Repeated subtraction among two numbers
- Check if N can be obtained by repetitive addition or subtraction of two given numbers
- Multiply large integers under large modulo
- Check perfect square using addition/subtraction
- Addition and Subtraction of Matrix using pthreads
- GCD of two numbers when one of them can be very large
- Sum of two large numbers
- LCM of two large numbers
- Last digit of Product of two Large or Small numbers (a * b)
- Sum of two large Floating-point numbers
- Difference of two large numbers
- Program for subtraction of matrices
- Square root of a number by Repeated Subtraction method
- Make all array elements equal by repeated subtraction of absolute difference of pairs from their maximum
- Multiply Large Numbers using Grid Method
- Factorial of Large numbers using Logarithmic identity
- Check if a large number can be divided into two or more segments of equal sum
- Find Last Digit of a^b for Large Numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.