首页 > 试题广场 >

计算器(二)

[编程题]计算器(二)
  • 热度指数:2065 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个字符串形式的表达式 s ,请你实现一个计算器并返回结果,除法向下取整。

数据范围:表达式长度满足 ,字符串中包含 + , - , * , / , 保证表达式合法。
示例1

输入

"1*10"

输出

10
示例2

输入

"8*9-19"

输出

53
示例3

输入

"100000*100*0"

输出

0
示例4

输入

"100000*100/9"

输出

1111111
package main
import _"fmt"
import "strconv"

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param s string字符串 
 * @return int整型
*/
func calculate( s string ) int {
    ints:=[]int{}
    symbols:=[]byte{}
    pre:=""
    for _,ch:=range []byte(s){
        if ch=='-'||ch=='+'{
            ints=append(ints,calc(pre))
            symbols=append(symbols,ch)
            pre=""
        }else{
            pre+=string(ch)
        }
    }
    ints=append(ints,calc(pre))
    ans:=ints[0]
    for i,x:=range ints[1:]{
        if symbols[i]=='-'{
            ans-=x
        }else{
            ans+=x
        }
    }
    return ans
}

func calc(s string)int{
    ints:=[]int{}
    symbols:=[]byte{}
    pre:=""
    for _,ch:=range []byte(s){
        if ch=='*'||ch=='/'{
            x,_:=strconv.Atoi(pre)
            ints=append(ints,x)
            symbols=append(symbols,ch)
            pre=""
        }else{
            pre+=string(ch)
        }
    }
    x,_:=strconv.Atoi(pre)
    ints=append(ints,x)
    ans:=ints[0]
    for i,x:=range ints[1:]{
        if symbols[i]=='*'{
            ans*=x
        }else{
            ans/=x
        }
    }
    return ans
}

发表于 2023-03-11 11:52:09 回复(0)

问题信息

难度:
1条回答 2252浏览

热门推荐

通过挑战的用户

查看代码