Created
November 25, 2019 05:08
-
-
Save adamgoose/0bfdc200ddbbada0a1477e6175a5e761 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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