Count the number of carry operations required to add two numbers | 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
def count_carry ( a , b ) : NEW_LINE INDENT carry = 0 ; NEW_LINE count = 0 ; NEW_LINE len_a = len ( a ) ; NEW_LINE len_b = len ( b ) ; NEW_LINE while ( len_a != 0 or len_b != 0 ) : NEW_LINE INDENT x = 0 ; NEW_LINE y = 0 ; NEW_LINE if ( len_a > 0 ) : NEW_LINE INDENT x = int ( a [ len_a - 1 ] ) + int ( '0' ) ; NEW_LINE len_a -= 1 ; NEW_LINE DEDENT if ( len_b > 0 ) : NEW_LINE INDENT y = int ( b [ len_b - 1 ] ) + int ( '0' ) ; NEW_LINE len_b -= 1 ; NEW_LINE DEDENT sum = x + y + carry ; NEW_LINE if ( sum >= 10 ) : NEW_LINE INDENT carry = 1 ; NEW_LINE count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT carry = 0 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT a = "9555" ; NEW_LINE b = "555" ; NEW_LINE count = count_carry ( a , b ) ; NEW_LINE if ( count == 0 ) : NEW_LINE INDENT print ( "0" ) ; NEW_LINE DEDENT elif ( count == 1 ) : NEW_LINE INDENT print ( "1" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( count ) ; NEW_LINE DEDENT