基本思路,先将其余进制转化为10进制,然后只需要写出来十进制的计算器就可以了。
总体代码如下:
package bishi.shunfeng;
import java.util.Scanner;
import java.util.Stack;
public class jsq {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
int n = scanner.nextInt();
String ss = Decimal_conversion(s,n);
System.out.println(calculate(ss,0)[0]);
}
/*
将n进制转化为10进制
*/
private static String Decimal_conversion(String s , int n){
int start = 0;
StringBuilder res = new StringBuilder();
while (!Character.isDigit(s.charAt(start))) {
res.append(s.charAt(start));
start++;
}
String temp = "";
for (int i = start; i < s.length(); i++) {
if(!Character.isDigit(s.charAt(i))){
if(!"".equals(temp))
{
res.append(""+Integer.parseInt(temp,n));
}
res.append(s.charAt(i));
temp = "";
}
if(Character.isDigit(s.charAt(i)))
{
temp += s.charAt(i);
}
if(i == s.length() - 1){
if(!"".equals(temp))
{
res.append(""+Integer.parseInt(temp,n));
}
}
}
return res.toString();
}
// 十进制计算器
public int calculate(String s) {
return calculate(s,0)[0];
}
private static int[] calculate(String s ,int index){
Stack<Integer> stack = new Stack<>();
int[] res = new int[2];
int num = 0;
char flag = '+';
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c =='(') {
int[] temp = calculate(s.substring(i + 1) ,i + 1);
num = temp[0];
if(temp[1] == s.length())
temp[1] = s.length() - 1;
c = s.charAt(temp[1]);
i = temp[1];
}
if(Character.isDigit(c)){
num = num * 10 + (c - '0' );
}
if(!Character.isDigit(c) && c != ' ' || c == ')' || i >= s.length() - 1){
switch (flag){
case '-':{
stack.push(-num); num = 0; flag = c ;break;
}
case '+': stack.push(num);num = 0; flag = c;break;
case '*':stack.push(stack.pop() * num); num = 0;flag = c; break;
case '/':stack.push((int) (stack.pop() / (float)num));num = 0 ; flag = c ; break;
}
}
if(c == ')') {
res[1] = i + 1 + index;
break;
}
}
res[0] = sum_stack(stack);
return res;
}
//对栈求值
private static int sum_stack(Stack<Integer> stack) {
int res = 0;
while (!stack.isEmpty()){
res += stack.pop();
}
return res;
}
}