Accenture Coding Question 6
Coding Question 6
A carry is a digit that is transferred to left if sum of digits exceeds 9 while adding two numbers from right-to-left one digit at a time
You are required to implement the following function, Int NumberOfCarries(int num1 , int num2);
The functions accepts two numbers ‘num1’ and ‘num2’ as its arguments. You are required to calculate and return the total number of carries generated while adding digits of two numbers ‘num1’ and ‘ num2’.
Assumption: num1, num2>=0
Example:
- Input
- Num 1: 451
- Num 2: 349
- Output
- 2
Explanation:
Adding ‘num 1’ and ‘num 2’ right-to-left results in 2 carries since ( 1+9) is 10. 1 is carried and (5+4=1) is 10, again 1 is carried. Hence 2 is returned.
Sample Input
Num 1: 23
Num 2: 563
Sample Output
0
C
Python
C++
Java
C
#include<stdio.h> int numberOfCarries(int num1 , int num2) { int carry = 0, sum, p, q, count = 0; while((num1!=0)&&(num2!=0)) { p = num1 % 10; q = num2 % 10; sum = carry + p + q; if(sum>9) { carry = 1; count++; } else { carry = 0; } num1 = num1/10; num2 = num2/10; } return count; } int main() { int x, y, a; scanf("%d",&x); scanf("%d",&y); a = numberOfCarries(x, y); printf("%d",a); return 0; }
Output:
23
563
0
Python
def NumberOfCarries(n1,n2): count=0 carry = 0 if len(n1) <= len(n2): l= len(n1)-1 else: l = len(n2)-1 for i in range(l+1): temp = int(n1[l-i])+int(n2[l-i])+carry if len(str(temp))>1: count+=1 carry = 1 else: carry = 0 return count+carry n1=input() n2=input() print(NumberOfCarries(n1,n2))
Output: 23 563 0
C++
#include<bits/stdc++.h>
using namespace std;
int numberOfCarries(int num1 , int num2)
{
int carry = 0, sum, p, q, count = 0;
while((num1!=0)&&(num2!=0))
{
p = num1 % 10;
q = num2 % 10;
sum = carry + p + q;
if(sum>9)
{
carry = 1;
count++;
}
else
{
carry = 0;
}
num1 = num1/10;
num2 = num2/10;
}
return count;
}
int main()
{
int x, y, res;
cin>>x>>y;
res = numberOfCarries(x, y);
cout<<res;
return 0;
}
Java
import java.util.*;
class Solution
{
public static int numberOfCarries (int num1, int num2)
{
int count = 0;
int temp1 = num1, temp2 = num2;
int rem = 0;
while (temp1 != 0 && temp2 != 0)
{
int d1 = temp1 % 10, d2 = temp2 % 10;
if ((d1 + d2 + rem) > 9)
{
count++;
int sum = d1 + d2 + rem;
sum = sum / 10;
rem = sum;
}
temp1 = temp1 / 10;
temp2 = temp2 / 10;
}
return count;
}
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int num1 = sc.nextInt ();
int num2 = sc.nextInt ();
System.out.println (numberOfCarries (num1, num2));
}
}