当前位置: 代码迷 >> 综合 >> HDOJ 1237 简单计算器
  详细解决方案

HDOJ 1237 简单计算器

热度:98   发布时间:2023-10-21 19:38:23.0

HDACM1237

思路:先把数字提取出来,然后定义2个指针left和right表示left到right范围内可计算,计算完的值就可以存在num[right],表示下标0~right的计算结果,同时需要一个标记flag用来区分计算的优先级(0的优先级最高,-1 or 1较次,-1表示left~right 是相减的,1表示left~right 是相加的)

import java.util.Scanner;public class Main{public static void main(String[] args) {Scanner sc= new Scanner(System.in);while (sc.hasNext()) {String str = sc.nextLine();if ("0".equals(str)) {break;}String strs[] = str.split(" ");double num[] = new double[strs.length];for (int i = 0; i < num.length; i+=2) {num[i] = Double.parseDouble(strs[i]);}double sum = Double.parseDouble(strs[0]);int flag = 0;int left = 0;int right = 0;int i =1;while (i < strs.length) {if ("+".equals(strs[i])) {if (right-left>0) {if (flag>0) {num[right] += num[left];left = right;flag = 0;}if (flag<0) {num[right] = num[left] - num[right];left = right;flag = 0;}}flag = 1;right = i+1;}if ("-".equals(strs[i])) {if (right-left>0) {if (flag>0) {num[right] += num[left];left = right;flag = 0;}if (flag<0) {num[right] = num[left] - num[right];left = right;flag = 0;}}flag = -1;right = i+1;}if ("*".equals(strs[i])) {right = i+1;num[right] = num[i-1] * num[right] ;if (flag == 0) {left = right;}}if ("/".equals(strs[i])) {right = i+1;num[right] = num[i-1]/num[right];if (flag == 0) {left = right;}}i += 2;}if (flag>0) {System.out.printf("%.2f",num[left]+num[right]);System.out.println();}if(flag<0){System.out.printf("%.2f",num[left]-num[right]);System.out.println();}if (flag==0) {System.out.printf("%.2f",num[i-1]);System.out.println();}}sc.close();}
}