[JAVA] ACM PrimaryArthmeticQ
Sample Input
123 456 555 555 123 594 0 0 |
Sample Output
No carry operation. 3 carry operations. 1 carry operation. |
I have a java code.
/** * * @author http://javaagkasit.blogspot.com/ */ import java.util.Scanner; public class PrimaryArthmeticQ { static int ten =10,zero = 0,one =1; private int ans = zero, carry = zero, totalcarry = zero; public static void main(String[] args)throws Exception{ Scanner sc = new Scanner(System.in); PrimaryArthmeticQ PAQ =new PrimaryArthmeticQ(); try{ while(true){ String inputS= sc.nextLine(); if(!inputS.equals("0 0")){ String[] input =inputS.split(" "); PAQ.process(input[zero], input[one]); PAQ.print(); }else{ System.out.print(""); break; } } }catch(Exception e){ System.out.println(e.getClass()); System.out.println("Re-enter.!!!"); } } public void process(String s1,String s2){ String ss1 = reverseStr(s1);//ตัวตั่ง String ss2 = reverseStr(s2);//ต้วบวก int last = lengthLoop(ss1,ss2);//จำหลักของตัวเลข int op=zero,op2=zero; for(int i =zero ; i < last ;i++){ if( i < ss1.length()) op = Integer.parseInt(ss1.charAt(i)+"");else op = zero; if( i < ss2.length()) op2 = Integer.parseInt(ss2.charAt(i)+"");else op2 = zero; add(op,op2);//ตัวตั่งกับ ต้วบวกบวกกัน } this.carry = zero;//clear carry =0 } public void print(){ if(totalcarry == one) System.out.println(totalcarry+" "+"carry operation."); else if(totalcarry == zero) System.out.println("No carry operation."); else System.out.println(totalcarry+" "+"carry operations."); this.totalcarry = zero;//clear totalcarry =0 } private void add(int op,int op2){ ans = op + op2 +carry; Ccarray(); } private void Ccarray(){ if(ans >= ten){ this.carry = one; totalcarry++; }else this.carry = zero; } private String reverseStr(String st){ StringBuffer str = new StringBuffer(st); str.reverse(); String ss = str.toString(); return ss; } private int lengthLoop(String s1,String s2){ int last=zero; if(s1.length() > s2.length()){ last=s1.length(); }else{ last=s2.length(); } return last; } } |