Count the number of carry operations required to add two numbers | C ++ implementation of above approach ; Function to count the number of carry operations ; Initialize the value of carry to 0 ; Counts the number of carry operations ; Initialize len_a and len_b with the sizes of strings ; Assigning the ascii value of the character ; Add both numbers / digits ; If sum > 0 , increment count and set carry to 1 ; Else , set carry to 0 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_carry ( string a , string b ) { int carry = 0 ; int count = 0 ; int len_a = a . length ( ) , len_b = b . length ( ) ; while ( len_a != 0 len_b != 0 ) { int x = 0 , y = 0 ; if ( len_a > 0 ) { x = a [ len_a - 1 ] - '0' ; len_a -- ; } if ( len_b > 0 ) { y = b [ len_b - 1 ] - '0' ; len_b -- ; } int sum = x + y + carry ; if ( sum >= 10 ) { carry = 1 ; count ++ ; } else carry = 0 ; } return count ; } int main ( ) { string a = "9555" , b = "555" ; int count = count_carry ( a , b ) ; if ( count == 0 ) cout << "0 STRNEWLINE " ; else if ( count == 1 ) cout << "1 STRNEWLINE " ; else cout << count << " STRNEWLINE " ; return 0 ; }