Difference of two large numbers
Given two numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find the difference between these two numbers.
Examples:
Input : str1 = "11443333311111111100",
str2 = "1144422222221111"
Output : 11442188888888889989
Input :str1 = "122387876566565674",
str2 = "31435454654554"
Output : 122356441111911120
This is simply based on school mathematics. We traverse both strings from the end, one by one subtract digits.
- Reverse both strings.
- Keep subtracting digits one by one from 0’th index (in reversed strings) to the end of a smaller string, append the diff if it’s positive to end of the result. If difference(diff) is negative then add 10 and keep track of carry as 1 if it’s positive then carry is 0.
- Finally, reverse the result.
Below is the implementation of the above idea:
C++
#include <bits/stdc++.h>
using namespace std;
bool isSmaller(string str1, string str2)
{
int n1 = str1.length(), n2 = str2.length();
if (n1 < n2)
return true ;
if (n2 < n1)
return false ;
for ( int i = 0; i < n1; i++)
if (str1[i] < str2[i])
return true ;
else if (str1[i] > str2[i])
return false ;
return false ;
}
string findDiff(string str1, string str2)
{
if (isSmaller(str1, str2))
swap(str1, str2);
string str = "" ;
int n1 = str1.length(), n2 = str2.length();
reverse(str1.begin(), str1.end());
reverse(str2.begin(), str2.end());
int carry = 0;
for ( int i = 0; i < n2; i++) {
int sub
= ((str1[i] - '0' ) - (str2[i] - '0' ) - carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str.push_back(sub + '0' );
}
for ( int i = n2; i < n1; i++) {
int sub = ((str1[i] - '0' ) - carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str.push_back(sub + '0' );
}
reverse(str.begin(), str.end());
return str;
}
int main()
{
string str1 = "978" ;
string str2 = "12977" ;
cout << findDiff(str1, str2) << endl;
string s1 = "100" ;
string s2 = "1000000" ;
cout << findDiff(s1, s2);
return 0;
}
|
Java
import java.util.*;
class GFG {
static boolean isSmaller(String str1, String str2)
{
int n1 = str1.length(), n2 = str2.length();
if (n1 < n2)
return true ;
if (n2 < n1)
return false ;
for ( int i = 0 ; i < n1; i++)
if (str1.charAt(i) < str2.charAt(i))
return true ;
else if (str1.charAt(i) > str2.charAt(i))
return false ;
return false ;
}
static String findDiff(String str1, String str2)
{
if (isSmaller(str1, str2)) {
String t = str1;
str1 = str2;
str2 = t;
}
String str = "" ;
int n1 = str1.length(), n2 = str2.length();
str1 = new StringBuilder(str1).reverse().toString();
str2 = new StringBuilder(str2).reverse().toString();
int carry = 0 ;
for ( int i = 0 ; i < n2; i++) {
int sub
= (( int )(str1.charAt(i) - '0' )
- ( int )(str2.charAt(i) - '0' ) - carry);
if (sub < 0 ) {
sub = sub + 10 ;
carry = 1 ;
}
else
carry = 0 ;
str += ( char )(sub + '0' );
}
for ( int i = n2; i < n1; i++) {
int sub = (( int )(str1.charAt(i) - '0' ) - carry);
if (sub < 0 ) {
sub = sub + 10 ;
carry = 1 ;
}
else
carry = 0 ;
str += ( char )(sub + '0' );
}
return new StringBuilder(str).reverse().toString();
}
public static void main(String[] args)
{
String str1 = "978" ;
String str2 = "12977" ;
System.out.println(findDiff(str1, str2));
String s1 = "100" ;
String s2 = "1000000" ;
System.out.println(findDiff(s1, s2));
}
}
|
Python3
def isSmaller(str1, str2):
n1 = len (str1)
n2 = len (str2)
if (n1 < n2):
return True
if (n2 < n1):
return False
for i in range (n1):
if (str1[i] < str2[i]):
return True
elif (str1[i] > str2[i]):
return False
return False
def findDiff(str1, str2):
if (isSmaller(str1, str2)):
temp = str1
str1 = str2
str2 = temp
str3 = ""
n1 = len (str1)
n2 = len (str2)
str1 = str1[:: - 1 ]
str2 = str2[:: - 1 ]
carry = 0
for i in range (n2):
sub = (( ord (str1[i]) - ord ( '0' )) - ( ord (str2[i]) - ord ( '0' )) - carry)
if (sub < 0 ):
sub = sub + 10
carry = 1
else :
carry = 0
str3 = str3 + str (sub)
for i in range (n2, n1):
sub = (( ord (str1[i]) - ord ( '0' )) - carry)
if (sub < 0 ):
sub = sub + 10
carry = 1
else :
carry = 0
str3 = str3 + str (sub)
str3 = str3[:: - 1 ]
return str3
if __name__ = = "__main__" :
str1 = "978"
str2 = "12977"
print (findDiff(str1, str2))
s1 = "100"
s2 = "1000000"
print (findDiff(s1, s2))
|
C#
using System;
using System.Collections;
class GFG {
static bool isSmaller( string str1, string str2)
{
int n1 = str1.Length, n2 = str2.Length;
if (n1 < n2)
return true ;
if (n2 < n1)
return false ;
for ( int i = 0; i < n1; i++)
if (str1[i] < str2[i])
return true ;
else if (str1[i] > str2[i])
return false ;
return false ;
}
static string findDiff( string str1, string str2)
{
if (isSmaller(str1, str2)) {
string t = str1;
str1 = str2;
str2 = t;
}
string str = "" ;
int n1 = str1.Length, n2 = str2.Length;
char [] ch1 = str1.ToCharArray();
Array.Reverse(ch1);
str1 = new string (ch1);
char [] ch2 = str2.ToCharArray();
Array.Reverse(ch2);
str2 = new string (ch2);
int carry = 0;
for ( int i = 0; i < n2; i++) {
int sub = (( int )(str1[i] - '0' )
- ( int )(str2[i] - '0' ) - carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += ( char )(sub + '0' );
}
for ( int i = n2; i < n1; i++) {
int sub = (( int )(str1[i] - '0' ) - carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += ( char )(sub + '0' );
}
char [] ch3 = str.ToCharArray();
Array.Reverse(ch3);
return new string (ch3);
}
public static void Main()
{
string str1 = "978" ;
string str2 = "12977" ;
Console.WriteLine(findDiff(str1, str2));
string s1 = "100" ;
string s2 = "1000000" ;
Console.WriteLine(findDiff(s1, s2));
}
}
|
PHP
<?php
function isSmaller( $str1 , $str2 )
{
$n1 = strlen ( $str1 );
$n2 = strlen ( $str2 );
if ( $n1 < $n2 )
return true;
if ( $n2 < $n1 )
return false;
for ( $i =0; $i < $n1 ; $i ++)
if ( $str1 [ $i ] < $str2 [ $i ])
return true;
else if ( $str1 [ $i ] > $str2 [ $i ])
return false;
return false;
}
function findDiff( $str1 , $str2 )
{
if (isSmaller( $str1 , $str2 )){
$t = $str1 ;
$str1 = $str2 ;
$str2 = $t ;
}
$str = "" ;
$n1 = strlen ( $str1 );
$n2 = strlen ( $str2 );
$str1 = strrev ( $str1 );
$str2 = strrev ( $str2 );
$carry = 0;
for ( $i =0; $i < $n2 ; $i ++)
{
$sub =((ord( $str1 [ $i ])-ord( '0' ))-(ord( $str2 [ $i ])-ord( '0' ))- $carry );
if ( $sub < 0)
{
$sub = $sub + 10;
$carry = 1;
}
else
$carry = 0;
$str .= chr ( $sub +48);
}
for ( $i = $n2 ; $i < $n1 ; $i ++)
{
$sub = ((ord( $str1 [ $i ])-ord( '0' )) - $carry );
if ( $sub < 0)
{
$sub = $sub + 10;
$carry = 1;
}
else
$carry = 0;
$str .= chr ( $sub +48);
}
$str = strrev ( $str );
return $str ;
}
$str1 = "978" ;
$str2 = "12977" ;
echo findDiff( $str1 , $str2 ). "\n" ;
$s1 = "100" ;
$s2 = "1000000" ;
echo findDiff( $s1 , $s2 );
?>
|
Javascript
<script>
function isSmaller(str1,str2)
{
let n1 = str1.length, n2 = str2.length;
if (n1 < n2)
return true ;
if (n2 < n1)
return false ;
for (let i = 0; i < n1; i++)
if (str1[i] < str2[i])
return true ;
else if (str1[i] > str2[i])
return false ;
return false ;
}
function findDiff(str1,str2)
{
if (isSmaller(str1, str2)) {
let t = str1;
str1 = str2;
str2 = t;
}
let str = "" ;
let n1 = str1.length, n2 = str2.length;
str1 = str1.split( "" ).reverse().join( "" )
str2 = str2.split( "" ).reverse().join( "" )
let carry = 0;
for (let i = 0; i < n2; i++)
{
let sub
= ((str1[i].charCodeAt(0) -
'0' .charCodeAt(0))
- (str2[i].charCodeAt(0) -
'0' .charCodeAt(0)) - carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += String.fromCharCode(sub +
'0' .charCodeAt(0));
}
for (let i = n2; i < n1; i++) {
let sub = ((str1[i].charCodeAt(0) -
'0' .charCodeAt(0)) - carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += String.fromCharCode(sub +
'0' .charCodeAt(0));
}
return str.split( "" ).reverse().join( "" )
}
let str1 = "978" ;
let str2 = "12977" ;
document.write(findDiff(str1, str2)+ "<br>" );
let s1 = "100" ;
let s2 = "1000000" ;
document.write(findDiff(s1, s2)+ "<br>" );
</script>
|
Time Complexity: O(n1 + n2)
Auxiliary Space: O(max(n1, n2))
Optimized solution :
We can avoid the first two string reverse operations by traversing them from the end.
Below is the optimized solution.
C++
#include <bits/stdc++.h>
using namespace std;
bool isSmaller(string str1, string str2)
{
int n1 = str1.length(), n2 = str2.length();
if (n1 < n2)
return true ;
if (n2 < n1)
return false ;
for ( int i = 0; i < n1; i++) {
if (str1[i] < str2[i])
return true ;
else if (str1[i] > str2[i])
return false ;
}
return false ;
}
string findDiff(string str1, string str2)
{
if (isSmaller(str1, str2))
swap(str1, str2);
string str = "" ;
int n1 = str1.length(), n2 = str2.length();
int diff = n1 - n2;
int carry = 0;
for ( int i = n2 - 1; i >= 0; i--) {
int sub = ((str1[i + diff] - '0' ) - (str2[i] - '0' )
- carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str.push_back(sub + '0' );
}
for ( int i = n1 - n2 - 1; i >= 0; i--) {
if (str1[i] == '0' && carry) {
str.push_back( '9' );
continue ;
}
int sub = ((str1[i] - '0' ) - carry);
if (i > 0 || sub > 0)
str.push_back(sub + '0' );
carry = 0;
}
reverse(str.begin(), str.end());
return str;
}
int main()
{
string str1 = "88" ;
string str2 = "1079" ;
cout << findDiff(str1, str2);
return 0;
}
|
Java
class GFG {
static boolean isSmaller(String str1, String str2)
{
int n1 = str1.length(), n2 = str2.length();
if (n1 < n2)
return true ;
if (n2 < n1)
return false ;
for ( int i = 0 ; i < n1; i++) {
if (str1.charAt(i) < str2.charAt(i))
return true ;
else if (str1.charAt(i) > str2.charAt(i))
return false ;
}
return false ;
}
static String findDiff(String str1, String str2)
{
if (isSmaller(str1, str2)) {
String t = str1;
str1 = str2;
str2 = t;
}
String str = "" ;
int n1 = str1.length(), n2 = str2.length();
int diff = n1 - n2;
int carry = 0 ;
for ( int i = n2 - 1 ; i >= 0 ; i--) {
int sub
= ((( int )str1.charAt(i + diff) - ( int ) '0' )
- (( int )str2.charAt(i) - ( int ) '0' )
- carry);
if (sub < 0 ) {
sub = sub + 10 ;
carry = 1 ;
}
else
carry = 0 ;
str += String.valueOf(sub);
}
for ( int i = n1 - n2 - 1 ; i >= 0 ; i--) {
if (str1.charAt(i) == '0' && carry > 0 ) {
str += "9" ;
continue ;
}
int sub = ((( int )str1.charAt(i) - ( int ) '0' )
- carry);
if (i > 0 || sub > 0 )
str += String.valueOf(sub);
carry = 0 ;
}
return new StringBuilder(str).reverse().toString();
}
public static void main(String[] args)
{
String str1 = "88" ;
String str2 = "1079" ;
System.out.println(findDiff(str1, str2));
}
}
|
Python3
def isSmaller(str1, str2):
n1 = len (str1)
n2 = len (str2)
if (n1 < n2):
return True
if (n2 < n1):
return False
for i in range (n1):
if (str1[i] < str2[i]):
return True
elif (str1[i] > str2[i]):
return False
return False
def findDiff(str1, str2):
if (isSmaller(str1, str2)):
str1, str2 = str2, str1
Str = ""
n1 = len (str1)
n2 = len (str2)
diff = n1 - n2
carry = 0
for i in range (n2 - 1 , - 1 , - 1 ):
sub = (( ord (str1[i + diff]) - ord ( '0' )) -
( ord (str2[i]) - ord ( '0' )) - carry)
if (sub < 0 ):
sub + = 10
carry = 1
else :
carry = 0
Str + = chr (sub + ord ( '0' ))
for i in range (n1 - n2 - 1 , - 1 , - 1 ):
if (str1[i] = = '0' and carry):
Str + = '9'
continue
sub = ( ord (str1[i]) - ord ( '0' )) - carry
if (i > 0 or sub > 0 ):
Str + = chr (sub + ord ( '0' ))
carry = 0
Str = Str [:: - 1 ]
return Str
str1 = "88"
str2 = "1079"
print (findDiff(str1, str2))
|
C#
using System;
class GFG {
static bool isSmaller( string str1, string str2)
{
int n1 = str1.Length, n2 = str2.Length;
if (n1 < n2)
return true ;
if (n2 < n1)
return false ;
for ( int i = 0; i < n1; i++) {
if (str1[i] < str2[i])
return true ;
else if (str1[i] > str2[i])
return false ;
}
return false ;
}
static string findDiff( string str1, string str2)
{
if (isSmaller(str1, str2)) {
string t = str1;
str1 = str2;
str2 = t;
}
String str = "" ;
int n1 = str1.Length, n2 = str2.Length;
int diff = n1 - n2;
int carry = 0;
for ( int i = n2 - 1; i >= 0; i--) {
int sub = ((( int )str1[i + diff] - ( int ) '0' )
- (( int )str2[i] - ( int ) '0' ) - carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += sub.ToString();
}
for ( int i = n1 - n2 - 1; i >= 0; i--) {
if (str1[i] == '0' && carry > 0) {
str += "9" ;
continue ;
}
int sub = ((( int )str1[i] - ( int ) '0' ) - carry);
if (i > 0 || sub > 0)
str += sub.ToString();
carry = 0;
}
char [] aa = str.ToCharArray();
Array.Reverse(aa);
return new string (aa);
}
public static void Main()
{
String str1 = "88" ;
String str2 = "1079" ;
Console.WriteLine(findDiff(str1, str2));
}
}
|
PHP
<?php
function isSmaller( $str1 , $str2 )
{
$n1 = strlen ( $str1 );
$n2 = strlen ( $str2 );
if ( $n1 < $n2 )
return true;
if ( $n2 < $n1 )
return false;
for ( $i = 0; $i < $n1 ; $i ++)
{
if ( $str1 [ $i ] < $str2 [ $i ])
return true;
else if ( $str1 [ $i ] > $str2 [ $i ])
return false;
}
return false;
}
function findDiff( $str1 , $str2 )
{
if (isSmaller( $str1 , $str2 ))
{
$t = $str1 ;
$str1 = $str2 ;
$str2 = $t ;
}
$str = "" ;
$n1 = strlen ( $str1 );
$n2 = strlen ( $str2 );
$diff = $n1 - $n2 ;
$carry = 0;
for ( $i = $n2 - 1; $i >= 0; $i --)
{
$sub = ((ord( $str1 [ $i + $diff ]) - ord( '0' )) -
(ord( $str2 [ $i ]) - ord( '0' )) - $carry );
if ( $sub < 0)
{
$sub = $sub + 10;
$carry = 1;
}
else
$carry = 0;
$str .= chr ( $sub + ord( "0" ));
}
for ( $i = $n1 - $n2 - 1; $i >= 0; $i --)
{
if ( $str1 [ $i ] == '0' && $carry > 0)
{
$str .= "9" ;
continue ;
}
$sub = (ord( $str1 [ $i ]) - ord( '0' ) - $carry );
if ( $i > 0 || $sub > 0)
$str .= chr ( $sub + ord( "0" ));
$carry = 0;
}
return strrev ( $str );
}
$str1 = "88" ;
$str2 = "1079" ;
print (findDiff( $str1 , $str2 ));
?>
|
Javascript
<script>
function isSmaller(str1, str2)
{
let n1 = str1.length, n2 = str2.length;
if (n1 < n2)
return true ;
if (n2 < n1)
return false ;
for (let i = 0; i < n1; i++) {
if (str1[i].charCodeAt() < str2[i].charCodeAt())
return true ;
else if (str1[i].charCodeAt() > str2[i].charCodeAt())
return false ;
}
return false ;
}
function findDiff(str1, str2)
{
if (isSmaller(str1, str2)) {
let t = str1;
str1 = str2;
str2 = t;
}
let str = "" ;
let n1 = str1.length, n2 = str2.length;
let diff = n1 - n2;
let carry = 0;
for (let i = n2 - 1; i >= 0; i--) {
let sub = ((str1[i + diff].charCodeAt() -
'0' .charCodeAt())
- (str2[i].charCodeAt() -
'0' .charCodeAt()) - carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str += sub.toString();
}
for (let i = n1 - n2 - 1; i >= 0; i--) {
if (str1[i] == '0' && carry > 0) {
str += "9" ;
continue ;
}
let sub = ((str1[i].charCodeAt() -
'0' .charCodeAt()) - carry);
if (i > 0 || sub > 0)
str += sub.toString();
carry = 0;
}
let aa = str.split('');
aa.reverse();
return aa.join( "" );
}
let str1 = "88" ;
let str2 = "1079" ;
document.write(findDiff(str1, str2));
</script>
|
Time complexity : O(n1 + n2)
Auxiliary Space: O(max(n1, n2))
Last Updated :
13 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...