So, I just came back from a CS Competition, and there was this one question that asked this:
"You will be given a .in file that will contain a number "n" which is the number of times to loop the program. The next lines will consist of two integers each that you will need to add. Develop a program to determine the number of arithmetic carries during this process"
For example: 9 + 1 = 10 ... You carried once
Data Input:
3
123 456
555 555
469 101
Output:
0
3
1
So here's my code that gave me the correct answers for the provided input:
import java.util.*; public class friday { public static void main(String args[]){ Scanner scan = new Scanner(System.in); System.out.println("Enter number of times to run"); int count = scan.nextInt(); while(count > 0){ System.out.println("Enter A:"); int a = scan.nextInt(); System.out.println("Enter B:"); int b = scan.nextInt(); String aword = a+""; String bword = b+""; char array1[] = aword.toCharArray(); char array2[] = bword.toCharArray(); int carries = 0; for(int i = array2.length; i > 0; i--){ if((array1[i-1] + array2[i-1]) > 9+48+48){ carries++; } } System.out.println(carries); count--; } } }
It doesn't work if the number's lengths are variable.. like A has a length of 2, and B has a length of 3.. It won't work that way, or if you have 999 + 1, the logic behind it wouldn't work either... Can someone point me in the correct direction? My friend who was in the advanced division told me he would use recursion.. But his logic was kind of skewed when he gave me an answer.. Any help would be Greatly Appreciated.