自己处理公式
問題說明:
給定一個字符串,例如:
String gsstring = "3565767 + 276756 * 76764 - 76 / 2 + 1";?如何將其當作數字運算,即相當于:
int gsint = 3565767 + 276756 * 76764 - 76 / 2 + 1;?我們如何來解析這樣一個簡單的公式(當前沒有括號參與操作 )。
?
第一步:將此字符串變換為字節數組,將問題轉換為針對字節數組的處理。
byte[] b = gsstring.getBytes();第二步:編寫工具方法。
??? 1、判定一個字節是否為數字。
final public static boolean isdig(byte ch) {return ch >= '0' && ch <= '9'; }??? 2、將所有的數字字節整理為一個真實的數字。
final public static int dig(byte[] b) {int record = 0;for (int i = 0; i < b.length; i++) {record = record * 10 + (b[i] - '0');}return record; }??? 3、將字節表示的符號轉換為真正的運算操作。
final public static int calc(int record1, int record2, byte oper) {int record = 0;switch (oper) {case '+':record = record1 + record2;break;case '-':record = record1 - record2;break;case '*':record = record1 * record2;break;case '/':record = record1 / record2;break;default:break;}return record; }第三步:解析字節數組,將其記錄為一個數字的集合以及一個符號的集合。
final public static Vector parse(byte[] b) {Vector v = new Vector();Vector dig = new Vector();Vector sgn = new Vector();byte[] bb = null;int size, j, k;for (int i = 0; i < b.length; i++) {size = 0;if (isdig(b[i])) {j = i;do {size++;j++;} while (j < b.length && isdig(b[j]));bb = new byte[size];j = i;k = 0;do {bb[k] = b[j];k++;j++;} while (j < b.length && isdig(b[j]));i = i + size - 1;dig.add(new Integer(dig(bb)));} else {sgn.add(Byte.valueOf(b[i]));}}v.add(sgn);v.add(dig);return v; }第四步:操作得到的結果。
提供思路:這種公式的特點是數字集合總是比符號集合多1,并且都是按照順序存儲的(現在采取的方案是這樣)。所以,根據先乘除后加減原則,檢索符號集合中的乘除后再檢索加減,數字集合位置索引與符號索引之間存在對應關系,不難發現的。
增加處理:
public static int test(String gs) {byte[] b = dealByte(gs.getBytes());Vector v = parse(b);Vector sgn = (Vector) v.elementAt(0);Vector dig = (Vector) v.elementAt(1);while (sgn.size() != 0) {for (int i = 0; i < sgn.size(); i++) {if ('*' == ((Byte) sgn.elementAt(i)).byteValue()|| '/' == ((Byte) sgn.elementAt(i)).byteValue()) {operate(sgn, dig, i);i--;}}for (int i = 0; i < sgn.size(); i++) {if ('+' == ((Byte) sgn.elementAt(i)).byteValue()|| '-' == ((Byte) sgn.elementAt(i)).byteValue()) {operate(sgn, dig, i);i--;}}}return ((Integer) dig.elementAt(0)).intValue(); }static private void operate(Vector sgn, Vector dig, int index) {int value = calc(((Integer) dig.elementAt(index)).intValue(),((Integer) dig.elementAt(index + 1)).intValue(), ((Byte) sgn.elementAt(index)).byteValue());sgn.remove(index);dig.setElementAt(new Integer(value), index);dig.remove(index + 1); }此方式完全應用了算式的特點,加入括號處理相對復雜。
如何擴展加入(){}[],變得更強大一點??思考
OK。
?
總結
- 上一篇: 缠论中枢python源码_缠论画中枢主图
- 下一篇: UDT源码剖析(二):UDT自带例程re