Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package src;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class Carry {
- public static void main(String[] args) throws IOException {
- Carry carry = new Carry();
- BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
- // Loop through every input line.
- String line = input.readLine();
- while (line != null && line.length() != 0) {
- if (line == "0 0") {
- return;
- }
- String[] inputNumbers = line.split(" ");
- int carryCount = carry.computeCarry(inputNumbers[0], inputNumbers[1]);
- // Grammar correction.
- if (carryCount == 0) {
- System.out.println("No carry operation.");
- }
- else {
- String s = (carryCount == 1) ? "" : "s";
- System.out.println(carryCount + " carry operation" + s + ".");
- }
- line = input.readLine();
- }
- input.close();
- }
- /*
- * Computes and prints the number of 'carry' operations when adding two
- * positive integers of <10 digits.
- */
- int computeCarry(String first, String second) {
- // ensure first is > second
- if (second.length() > first.length()) {
- String temp = second;
- second = first;
- first = temp;
- }
- // reverse the strings, to make indexing possible.
- first = new StringBuffer(first).reverse().toString();
- second = new StringBuffer(second).reverse().toString();
- // The total number of cary operations for this sum.
- int carryCount = 0;
- // The number we 'carry' over to the next column. Only ever zero or 1.
- int carryOver = 0;
- // Loop through the number sequence, adding each digit and
- // the carry '1' where applicable, incrementing carryCount for every carry
- for (int i = 0; i < second.length() ; i ++) {
- int digitOne = Integer.parseInt(first.substring(i, i+1));
- int digitTwo = Integer.parseInt(second.substring(i, i+1));
- int sum = digitOne + digitTwo + carryOver;
- System.out.println(digitOne + " + " + digitTwo + " + " + carryOver + " (cC: " + carryCount + ")");
- // If the sum of this column is 10 or more, we need to carry.
- if (sum >= 10) {
- carryCount++;
- carryOver = 1;
- }
- else {
- carryOver = 0;
- }
- }
- return carryCount;
- }
- }
Add Comment
Please, Sign In to add comment