Skip to content

Instantly share code, notes, and snippets.

@vderyagin
Last active December 12, 2015 02:48
Show Gist options
  • Save vderyagin/4701101 to your computer and use it in GitHub Desktop.
Save vderyagin/4701101 to your computer and use it in GitHub Desktop.
package atoi_itoa
import (
"fmt"
"regexp"
)
func atoi(s string) (int, error) {
re := regexp.MustCompile(`^-?\d+$`)
if !re.MatchString(s) {
return 0, fmt.Errorf("'%s' is not a valid number")
}
var negative bool
if runes := []rune(s); runes[0] == '-' {
negative = true
s = string(runes[1:])
}
result := 0
for _, r := range s {
result *= 10
result += int(r - '0')
}
if negative {
return -result, nil
}
return result, nil
}
func itoa(i int) string {
if i == 0 {
return "0"
}
result := make([]rune, 0)
var negative bool
if i < 0 {
negative = true
i = -i
}
for n := i; n > 0; n /= 10 {
result = append(result, '0'+rune(n%10))
}
if negative {
result = append(result, '-')
}
for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
result[i], result[j] = result[j], result[i]
}
return string(result)
}
package atoi_itoa
import "testing"
func TestAtoiZero(t *testing.T) {
actual, err := atoi("0")
expected := 0
if err != nil {
t.Error(err)
}
if actual != expected {
t.Errorf("%d != %d", actual, expected)
}
}
func TestAtoiOne(t *testing.T) {
actual, err := atoi("1")
expected := 1
if err != nil {
t.Error(err)
}
if actual != expected {
t.Errorf("%d != %d", actual, expected)
}
}
func TestAtoiLongerNumbers(t *testing.T) {
actual, err := atoi("123890")
expected := 123890
if err != nil {
t.Error(err)
}
if actual != expected {
t.Errorf("%d != %d", actual, expected)
}
}
func TestAtoiNegativeNumbers(t *testing.T) {
actual, err := atoi("-123890")
expected := -123890
if err != nil {
t.Error(err)
}
if actual != expected {
t.Errorf("%d != %d", actual, expected)
}
}
func TestAtoiInvalidInput(t *testing.T) {
input := "abc"
_, err := atoi(input)
if err == nil {
t.Errorf("%s is not valid input", input)
}
input = "--123"
_, err = atoi(input)
if err == nil {
t.Errorf("%s is not valid input", input)
}
}
func TestItoaZero(t *testing.T) {
actual := itoa(0)
expected := "0"
if actual != expected {
t.Errorf("%s != %s", actual, expected)
}
}
func TestItoaOne(t *testing.T) {
actual := itoa(1)
expected := "1"
if actual != expected {
t.Errorf("%s != %s", actual, expected)
}
}
func TestItoaLongerNumbers(t *testing.T) {
actual := itoa(12300890)
expected := "12300890"
if actual != expected {
t.Errorf("%s != %s", actual, expected)
}
}
func TestItoaNegativeNumbers(t *testing.T) {
actual := itoa(-12300890)
expected := "-12300890"
if actual != expected {
t.Errorf("%s != %s", actual, expected)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment