Skip to main content

Posts

Showing posts with the label sum

Calculate and return the total number of carries generated while adding digits of two numbers

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, cou...

Find all pairs of an integer array or list whose sum is equal to a given number

Ex:-   [ 2, 4, 3, 5, 1, 6, 0 ]     and  5                      (2, 3)  ==> 2 + 3 = 5                      (4, 1) ==> 4 + 1 = 5                       (5, 0) ==> 5 + 0 = 5 Java 1 2 3 4 5 6 7 8 9 10 public class ArraySum { public static void main (String []args){ int [] arr = { 2 , 4 , 3 , 5 , 1 , 6 , 0 }; int given_sum = 5 ; for ( int i= 0 ; i<arr. length ; i++) for ( int j=i+ 1 ; j<arr. length ; j++) if (arr[i]+arr[j]==given_sum) System. out . println (arr[i]+ " " +arr[j]); } } Python given_list = [ 2 , 4 , 3 , 5 , 1 , 6 , 0 ] given_sum = 5 for i in rang...