public static String format(long number, long n) { 链栈的接口.LinkStack <string> s = new 链栈.LinkStack <string>(); String data = "0123456789ABCDEF"; while (number > 0) { int remainder = (int)(number % n); string x = data[remainder].ToString(); s.Push(x); number /= n; } string result = ""; while (s.Count > 0) { result += s.Pop(); } return(result); }
public static bool check(string str) { if (str.Equals("")) { return(false); } if (str == ".") { return(false); } //如果有连续的符号的话返回false if (Regex.IsMatch(str, @"[+-/\\*]{2,}")) { return(false); } //如果出现连续的括号的话返回false if (Regex.IsMatch(str, @"[\(\)]{2,}")) { return(false); } //如果左括号后面出现+*/符号的时候返回false if (Regex.IsMatch(str, @"\([+/\\*]+")) { return(false); } //如果右括号后面出现数字或者没有出现+-*/的时候返回false if (Regex.IsMatch(str, @"\)[^+-/\\*]")) { return(false); } //如果左括号前面没有出现+-*/的时候返回false if (Regex.IsMatch(str, @"[^+-/\\*]+\(")) { return(false); } //如果右括号前面出现+-*/的时候返回fasle if (Regex.IsMatch(str, @"[+-/\\*]+\)")) { return(false); } //递归检查括号是否成对出现 char item; 链栈的接口.LinkStack <string> s = new 链栈.LinkStack <string>(); for (int i = 0; i < str.Length; i++) { item = str[i]; if (item == '(') { s.Push("("); } else if (item == ')') { if (s.Count > 0) { s.Pop(); } else { return(false); } } } if (s.Count != 0) { return(false); } return(true); }
//总体调用函数 internal static string BackPoland(string expression) { 链栈的接口.LinkStack <string> operStack = new 链栈.LinkStack <string>(); 链栈的接口.LinkStack <string> numStack = new 链栈.LinkStack <string>(); operStack.Push("#"); //进栈 便于比较 string token = ""; for (int i = 0; i < expression.Length; i++) { if (IsNumber(expression[i].ToString()) || expression[i].ToString() == ".") //如果是数字 { token += expression[i].ToString(); } else if (expression[i].ToString() == "(") //左括号直接进栈 { operStack.Push(expression[i].ToString()); if (IsNumber(token)) { numStack.Push(token); } token = ""; } else if (IsSiZe(expression[i].ToString())) { if (IsNumber(token)) { numStack.Push(token); } token = ""; int item = Level(expression[i].ToString()).CompareTo(Level(operStack.Peek())); //比较运算符优先级 if (item > 0) //如果优先级高于栈顶,运算符进栈 { operStack.Push(expression[i].ToString()); } else //如果运算符小于或等于栈顶 进行计算 并将运算符进栈 { Calc(numStack, operStack); operStack.Push(expression[i].ToString()); } } else if (expression[i].ToString() == ")") //如果遇到右括号 依次遍历进行计算直至遇到左括号 { if (IsNumber(token)) { numStack.Push(token); } token = ""; while (operStack.Peek() != "(") { Calc(numStack, operStack); } token = numStack.Pop(); //拿出数字便于进行下一次计算 operStack.Pop(); //符合条件的左括号出栈 } else //遍历结束 { if (IsNumber(token)) { numStack.Push(token); } token = ""; while (numStack.Count > 1) { Calc(numStack, operStack); } } } return(numStack.Pop()); }