2012年5月19日 星期六

Java 中序式轉後序式


import java.util.*;

public class Postfix{
    public static int priority(String str){
        switch( str ){
            case "+": case "-": 
                return 1;
            case "*": case"/": case "%": 
                return 2;
            default: 
                return 0;
        }
    }

    public static String toPostfix(String str){
        StringBuffer sb = new StringBuffer();
        LinkedList<String> stack = new LinkedList<String>();
        for(String sub : str.split(" ") ){
            if("(".indexOf(sub) != -1){
                stack.add(sub);
            }else if("+-*/%".indexOf(sub) != -1){
                while(!stack.isEmpty() && priority(stack.getLast()) >= priority(sub)){
                    sb.append(stack.removeLast() + " ");
                }
                stack.add(sub);
            }else if(")".indexOf(sub) != -1){
                while( "(".indexOf(stack.getLast()) == -1 ){
                    sb.append(stack.removeLast() + " ");
                }
                stack.removeLast();
            }else{
                sb.append(sub + " ");
            }
        }
  
        while(!stack.isEmpty()){ sb.append(stack.removeLast()); }
        return sb.toString();
    }
 
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str;
  
        while( sc.hasNext() ){
            str = sc.nextLine();
            System.out.println( toPostfix(str) );
        }
    }
}

參考:良葛格學習筆記

2012年5月13日 星期日

Java 大數運算


import java.util.*;
import java.math.*;

public class BigNumberCount{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str;
  
        while( sc.hasNext() ){
            str = sc.nextLine();
            StringBuffer sb = new StringBuffer(str);
   
            String str1 = sb.substring(0, sb.indexOf(" "));
            sb.delete(0, sb.indexOf(" ")+1);
            String symbol = sb.substring(0, sb.indexOf(" "));
            String str2 = sb.substring(sb.indexOf(" ")+1, sb.length());
            
            BigInteger a = new BigInteger(str1);
            BigInteger b = new BigInteger(str2);
   
            switch( symbol.charAt(0) ){
                case '+':
                    System.out.println( a.add(b) );
                    break;
                case '-':
                    System.out.println( a.subtract(b) );
                    break;
                case '*':
                    System.out.println( a.multiply(b) );
                    break;
                case '/':
                    System.out.println( a.divide(b) );
                    break;
            }  
        }
    }
}

說明

直接使用Java.math底下的BigInteger類別實做

題目

大數運算

參考

超長整數運算(大數運算)