Ex:- 174 + 487 ==> (4+7) = 11 so we write only 1 and 1 is the carry similarly (7+8+1carry) = 16 so we write 6 and 1 will be carry now (1+4+1carry) = 6 so the sum is 661
here , total carry generated is 2.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class Carry{ public static void main(String []args){ int num1=289, num2=12; System.out.print(countCarry(num1,num2)); } public static int countCarry(int num1, int num2){ int carry=0, count=0; while(num1!=0 || num2!=0){ if(((num1%10)+(num2%10)+carry)>9){ carry = 1; count += 1; } else carry = 0; num1 = num1 / 10; num2 = num2 / 10; } return count; } } |
Python
def countCarry(num1, num2): carry, count = 0,0 while num1!=0 or num2!=0: if (num1%10)+(num2%10)+carry > 9: carry = 1 count += 1 else: carry = 0 num1 = num1//10 num2 = num2//10 return count num1, num2 = 289, 12 print(countCarry(num1, num2)) |