华为机试题:火星计算器 java版本

题目为:

自定义运算符@,#,$,&,并且优先级@>#>$>&,利用下面的计算法则,计算出一个给定的字符串表示的表达式的值,返回整型结果。

x@y = (x-1)*(y+1);

x#y = (2*x+5)*(3*y+60)

x$y = (x+1)*(2*x+3)*(y-1)*(2*y-3)

x&y = ((x+y+1)*(y-9)+(x+7)/(y-8))

输入:接受多行输入,每行可能有空格。

题目保证不会出现除数为0的情况,且所有操作数都是整数。为了简单起见,表达式不含有括号。

输出:对于每一行输入,输出一个运算结果。

输入:输出:

1@2=0

1#2=462

1@1@1=-2

1#1#1=55881

1$1$1=0

1&1&1=186

1#1@1=420

1@1#1=315

1$1&1=-17

1&1$1=-19

1# 1 & 1 =-3608

12 @ 12=143

123 @ 123=15128


java代码:

<pre name="code" class="java">import java.util.Scanner;

public class test {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		String string = scanner.nextLine();
		char c[] = { '@', '#', '$', '&' };
		string = string.replace(" ", "");
		for (int i = 0; i < c.length; i++) {
			while (string.indexOf(c[i]) != -1) {
				string = compute(string, c[i]);
			}

		}
		System.out.println(Integer.parseInt(string));
		scanner.close();
	}

	private static String compute(String string, char c) {
		int x = 0, y = 0;
		int a = string.indexOf(c);
		char b[] = string.toCharArray();
		for (int i = a + 1; i < b.length; i++) {
			if (('@' != b[i]) && ('#' != b[i]) && ('$' != b[i])
					&& ('&' != b[i])) {
				x++;

			} else if (('@' == b[i]) || ('#' == b[i]) || ('$' == b[i])
					|| ('&' == b[i])) {
				break;
			}

		}
		for (int j = a - 1; j >= 0; j--) {
			if (('@' != b[j]) && ('#' != b[j]) && ('$' != b[j])
					&& ('&' != b[j])) {
				y++;

			} else if (('@' == b[j]) || ('#' == b[j]) || ('$' == b[j])
					|| ('&' == b[j])) {
				break;
			}
		}
		String e = string.substring(a - y, a);//得到1@2#3的1
		String f = string.substring(a + 1, a + 1 + x);//得到1@2#3的2
		String g = string.substring(a - y, a + 1 + x);//得到1@2#3的1@2
		int eInt = Integer.parseInt(e);
		int fInt = Integer.parseInt(f);
		int rInt = 0;
		switch (c) {
		case '@':
			rInt = (eInt - 1) * (fInt + 1);
			break;
		case '#':
			rInt = (2 * eInt + 5) * (3 * fInt + 60);
			break;
		case '$':
			rInt = (eInt + 1) * (2 * eInt + 3) * (fInt - 1) * (2 * fInt - 3);
			break;
		case '&':
			rInt = ((eInt + fInt + 1) * (fInt - 9) + (eInt + 7) / (fInt - 8));
			break;
		default:
			break;
		}
		String rString = String.valueOf(rInt);
		string = string.replace(g, rString);//1@2#3变成rString#3
		return string;

	}

}



                
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值