-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path355.go
77 lines (66 loc) · 1.31 KB
/
355.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// UVa 355 - The Bases Are Loaded
package main
import (
"fmt"
"os"
)
type number struct {
b1, b2 int
num string
}
var nums []number
func toStr(d int) string {
if d <= 9 {
return string('0' + d)
}
return string('A' - 10 + d)
}
func getNumber(digit rune) int {
if digit >= '0' && digit <= '9' {
return int(digit - '0')
}
if digit >= 'A' && digit <= 'Z' {
return int(digit-'A') + 10
}
return -1
}
func base10(num string, base int) int {
var total int
for _, d := range num {
digit := getNumber(d)
if digit >= base {
return -1
}
total = total*base + digit
}
return total
}
func baseN(num int, base int) string {
var number string
for num > 0 {
digit := num % base
number = toStr(digit) + number
num = (num - digit) / base
}
return number
}
func main() {
in, _ := os.Open("355.in")
defer in.Close()
out, _ := os.Create("355.out")
defer out.Close()
var num number
for {
if _, err := fmt.Fscanf(in, "%d%d%s", &num.b1, &num.b2, &num.num); err != nil {
break
}
nums = append(nums, num)
}
for _, number := range nums {
if bt := base10(number.num, number.b1); bt == -1 {
fmt.Fprintf(out, "%s is an illegal base %d number\n", number.num, number.b1)
} else {
fmt.Fprintf(out, "%s base %d = %s base %d\n", number.num, number.b1, baseN(bt, number.b2), number.b2)
}
}
}