# Need help to solve a problem

Hi can someone help me to solve this? Input: s := “2+3-4” Output: 2+3-4 = 1. I am new with programming.

Can you provide a little more context, for example, is two digit numbers allowed? Are other operators allowed (other than + and -)?

Basically, you either need to write a simple parser that checks every character of the string, from left to right. And finally, when you have all the values and operators, you’ll need to sum it up. This of course gets more complicated if two digit values are allowed, and if more operators are allowed. And even more complicated if float values are allowed, etc. Then you are basically coding a calculator…

Alternatively, you can try to find a package that contains a “calculator” that takes a string and returns a number. I am sure that exists, but this solution will probably not be allowed if this is school work.

Hi, thank you for the replay. It is a single digit and it includes only the “+” and “-” operators. I will try to make a calculator aswell.

I solved the problem in a raw way.
package main

import (

``````"fmt"

"os"

"strconv"
``````

)

/* This function sum the ints if we have a ‘+’ sign else we have a difference */

func sumDiff(s []rune) int {

``````num1, num2 := 0, 0

tot := 0

for i := 0; i <= len(s)-1; i++ {

if s[i] == '+' && i <= 2 {

num1, _ = strconv.Atoi(string(s[i-1]))

num2, _ = strconv.Atoi(string(s[i+1]))

tot = tot + num1 + num2

} else if s[i] == '+' && i > 2 {

num2, _ = strconv.Atoi(string(s[i+1]))

tot = tot + num2

} else if s[i] == '-' && i <= 2 {

num1, _ = strconv.Atoi(string(s[i-1]))

num2, _ = strconv.Atoi(string(s[i+1]))

tot = tot + num1 - num2

} else if s[i] == '-' && i > 2 {

num2, _ = strconv.Atoi(string(s[i+1]))

tot = tot - num2

}

}

``````

}

/* This function converts a string elements into a slice */

func convStringSlice(s string) []rune {

``````contenitore := []rune{}

for _, c := range s {

contenitore = append(contenitore, (c))

}

return contenitore
``````

}

/* This function converts a slice of strings from line argument into a string */

func conv(s []string) string {

``````stringa := ""

for i := 0; i <= len(s)-1; i++ {

stringa = stringa + s[i]

}

return stringa
``````

}

func main() {

``````x := os.Args[1:]

testo := conv(x)

fmt.Println(testo, "=", sumDiff(convStringSlice(testo)))
``````

}

The infix expression is converted to the suffix expression, and then the stack is pushed and processed in turn. There are examples of this in the Chinese University Data Structure Tutorial.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.