阅读 3362 次
发表时间:2010-08-19
   刚才在另一个帖子里看到这个面试题,自己试着做了下。本来觉得很容易实现的居然写了1小时,被split搞晕了,用split("[\\d]+") 截取保存运算符的数组,下标0始终是空的,搞不清楚原因,只好remove掉才能得出正确的值。我的做法是把String截取为两个ArrayList,numList保存数字,operatorList保存运算符,遍历运算符数组operatorList,计算numList中下标为i和i+1的数的值,把值赋给i ,然后删掉numList中的i+1和operatorList中的i,i-- 。先算乘除后加减共遍历两次,最后返回numList.get(0) 。
  
   感觉自己的方法有点烂,代码冗余太多,很不优雅。希望大家来分享下自己的思路,让我借鉴学习下


import java.util.*;

public class ComputeString {

    public static void main(String[] args) {
        System.out.println(computeString("321+432*43/7+1"));
    }

    public static Double computeString(String s) {
        ArrayList<Double> numList = new <Double>ArrayList();
        ArrayList<String> operatorList = new <String>ArrayList();
        String[] nL = s.split("[+-/*]");
        String[] oL = s.split("[\\d]+");
      
        for (String str : nL) {
            numList.add(Double.parseDouble(str));
        }
        for (String str : oL) {
            operatorList.add(str);
        }
        operatorList.remove(0);
       

        for (int i = 0; i < operatorList.size(); i++) {
            switch (operatorList.get(i).charAt(0)) {
                case '*': {
                    numList.set(i, numList.get(i) * numList.get(i + 1));
                    numList.remove(i + 1);
                    operatorList.remove(i);
                    i--;
                    break;
                }
                case '/': {
                    numList.set(i, numList.get(i) / numList.get(i + 1));
                    numList.remove(i + 1);
                    operatorList.remove(i);
                    i--;
                    break;
                }
            }
        }

        for (int i = 0; i < operatorList.size(); i++) {
            switch (operatorList.get(i).charAt(0)) {
                case '+': {
                    numList.set(i, numList.get(i) + numList.get(i + 1));
                    numList.remove(i + 1);
                    operatorList.remove(i);
                    i--;
                    break;
                }
                case '-': {
                    numList.set(i, numList.get(i) - numList.get(i + 1));
                    numList.remove(i + 1);
                    operatorList.remove(i);
                    i--;
                    break;
                }
            }
        }
        return numList.get(0);
    }
}
发表时间:2010-10-17
不知道有什么更好的方法可以实现这个?我也来试试
发表时间:2010-10-17
呵呵,腾讯一面面试官有问这个~~~~~
发表时间:2010-10-18
经典的二叉树问题
Global site tag (gtag.js) - Google Analytics