日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

自己处理公式

發布時間:2023/12/20 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 自己处理公式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題說明:

給定一個字符串,例如:

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。

?

總結

以上是生活随笔為你收集整理的自己处理公式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。