仿LISP运算

标题:仿LISP运算 | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
LISP语言唯一的语法就是括号要配对。
形如 (OP P1 P2 ...),括号内元素由单个空格分割。



package main

import (
	"errors"
	"fmt"
	"math"
)

func main() {
	str := []uint8{}
	for {
		var tmp uint8
		fmt.Scanf("%c", &tmp)
		if tmp == '\n' {
			break
		}
		str = append(str, tmp)
	}
	res, err := foo(string(str))
	if err != nil {
		fmt.Println("error")
	} else {
		fmt.Println(res)
	}
}

func foo(data string) (int, error) {
	i := 0
	tmp := []string{}
	length := len(data)
	for i < length {
		if data[i] == '(' {
			tmp = append(tmp, data[i+1:i+4])
			i += 4
		} else if data[i] == ' ' {
			i++
		} else if data[i] == ')' {
			lenTmp := len(tmp)
			num1 := strToInt(tmp[lenTmp-1])
			num2 := strToInt(tmp[lenTmp-2])
			operate := tmp[lenTmp-3]
			tmp = tmp[:lenTmp-3]
			switch operate {
			case "add":
				tmp = append(tmp, fmt.Sprintf("%d", num1+num2))
				break
			case "sub":
				tmp = append(tmp, fmt.Sprintf("%d", num2-num1))
				break
			case "div":
				if num1 == 0 {
					return 0, errors.New("除0错误")
				}
				tmp = append(tmp, fmt.Sprintf("%.0f", math.Floor(float64(num2)/float64(num1))))
				break
			case "mul":
				tmp = append(tmp, fmt.Sprintf("%d", num1*num2))
				break
			}
			i++
		} else {
			start := i
			for data[i] != ' ' && data[i] != ')' {
				i++
			}
			tmp = append(tmp, data[start:i])
		}
	}
	return strToInt(tmp[0]), nil
}

func strToInt(str string) int {
	res, s, f, length := 0, 0, 1, len(str)
	if str[0] == '-' {
		f = -1
		s = 1
	}
	for s < length {
		res = res*10 + int(str[s]-'0')
		s++
	}
	return res * f
}
<?php
fscanf(STDIN, "%[^\n]s", $str);
$a = preg_match("/\(([^()]+?)\)/",$str,$match);
while(preg_match("/\(([^()]+?)\)/",$str,$match)){
  
  $val = trim($match[1]);
  $word = explode(' ',$val);
  $a = 0;
  switch($word[0]){
    case 'add':
      $a = $word[1] + $word[2];
      break;
    case 'sub':
      $a = $word[1] - $word[2];
      break;
    case 'mul':
      $a = $word[1] * $word[2];
      break;
    case 'div':
      if ($word[2] == 0){
        echo "error";
        die;
      }
      $a = ($word[1] / $word[2]);
      break;
  }
  $str = str_replace('('.$match[1].')',$a,$str);
}
$str = trim($str);
$word = explode($str);
if(count($word) > 1){
  switch($word[0]){
    case 'add':
      $a = $word[1] + $word[2];
      break;
    case 'sub':
      $a = $word[1] - $word[2];
      break;
    case 'mul':
      $a = $word[1] * $word[2];
      break;
    case 'div':
      if ($word[2] == 0){
        echo "error";
        die;
      }
      $a = ($word[1] / $word[2]);
      break;
  }
  echo $a;
  die;
}
echo $str;



全部评论

相关推荐

给🐭🐭个面试机会...:我擦seed✌🏻
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务