Guest User

Untitled

a guest
Jan 23rd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1. package src;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6.  
  7.  
  8. public class Carry {
  9.    
  10.     public static void main(String[] args) throws IOException {
  11.         Carry carry = new Carry();
  12.         BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
  13.        
  14.         String line;
  15.        
  16.         while ((line = input.readLine()) != null && line.length() != 0) {
  17.             String[] inputNumbers = line.split(" ");
  18.             int first = Integer.parseInt(inputNumbers[0]);
  19.             int second = Integer.parseInt(inputNumbers[1]);
  20.             int carryCount = carry.computeCarry(first, second);
  21.            
  22.             if (carryCount == 0) {
  23.                 System.out.println("No carry operation.");
  24.             }
  25.             else {
  26.                 String s = (carryCount == 1) ? "" : "s";
  27.                 System.out.println(carryCount + " carry operation" + s + ".");
  28.             }
  29.         }
  30.     }
  31.    
  32.     /*
  33.      * Computes and prints the number of 'carry' operations when adding two
  34.      * positive integers of <10 digits.
  35.      */
  36.     private int computeCarry(int first, int second) {      
  37.         // ensure first is > second
  38.         if (second > first) {
  39.             int temp = second;
  40.             second = first;
  41.             first = temp;
  42.         }
  43.        
  44.         int carryCount = 0;
  45.         int carryOver = 0;
  46.         for (int i = 1; i < (Integer.toString(second).length()); i ++) {
  47.             int carry = (int) ((first % Math.pow(10, i)) + (second % Math.pow(10, i))) + carryOver;
  48.             if (carry >= 10) {
  49.                 carryCount++;
  50.                 carryOver = carry % 10;
  51.             }
  52.         }
  53.         return carryCount;
  54.     }
  55.    
  56.    
  57.  
  58. }
Add Comment
Please, Sign In to add comment