Skip to content

Instantly share code, notes, and snippets.

@adamgoose
Created November 25, 2019 05:08
Show Gist options
  • Save adamgoose/0bfdc200ddbbada0a1477e6175a5e761 to your computer and use it in GitHub Desktop.
Save adamgoose/0bfdc200ddbbada0a1477e6175a5e761 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
)
func main() {
// Read the Reverse Polish Expression from Stdin
in, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal("Unable to read input")
}
equation := strings.Split(string(in), " ")
results := []uint64{}
for _, part := range equation {
if n, err := strconv.ParseUint(part, 10, 32); err == nil {
// Is numeric
results = append(results, n)
} else {
// Is operator
// Pick operands
left := results[len(results)-2]
right := results[len(results)-1]
results = results[:len(results)-2]
// Perform operation
var out uint64
switch part {
case "+":
out = left + right
break
case "-":
out = left - right
break
case "*":
out = left * right
break
case "/":
out = left / right
break
}
results = append(results, out)
}
log.Printf("WIP Results: %v\n", results)
}
if len(results) != 1 {
log.Fatal("Error in computation")
}
fmt.Println(results[0])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment