diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..4db9571 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/ordinary-dev/my-solutions + +go 1.19 diff --git a/leetcode/0007-reverse-integer/main.go b/leetcode/0007-reverse-integer/main.go new file mode 100644 index 0000000..cbec4ff --- /dev/null +++ b/leetcode/0007-reverse-integer/main.go @@ -0,0 +1,30 @@ +package main + +import ( + "math" +) + +func reverse(x int) int { + var res int32 + + var mul int32 = 1 + if x < 0 { + mul = -1 + x *= -1 + } + + for x != 0 { + digit := mul * int32(x % 10) + if mul > 0 && (math.MaxInt32 - digit) / 10 < res { + return 0 + } + if mul < 0 && (math.MinInt32 - digit) / 10 > res { + return 0 + } + + res = res * 10 + digit + x /= 10 + } + + return int(res) +} diff --git a/leetcode/0007-reverse-integer/main_test.go b/leetcode/0007-reverse-integer/main_test.go new file mode 100644 index 0000000..747be6e --- /dev/null +++ b/leetcode/0007-reverse-integer/main_test.go @@ -0,0 +1,21 @@ +package main + +import ( + "testing" + "math" +) + +func TestReverse(t *testing.T) { + if res := reverse(123); res != 321 { + t.Fatalf("%v != 321", res) + } + if res := reverse(-123); res != -321 { + t.Fatalf("%v != -321", res) + } + if res := reverse(120); res != 21 { + t.Fatalf("%v != 12", res) + } + if res := reverse(math.MaxInt32); res != 0 { + t.Fatalf("%v != 0", res) + } +} diff --git a/readme.md b/readme.md index 97b80df..1821807 100644 --- a/readme.md +++ b/readme.md @@ -16,6 +16,13 @@ cd random-problem ruby test.rb ``` +Go: + +```bash +cd random-problem +go test ./... +``` + ## Why Ruby? Solving problems in Ruby can be a lot more fun than it first appears. @@ -23,3 +30,7 @@ It is relatively slow language. Sub-optimal C or Rust solutions will pass all tests, but Ruby or Python solutions will not be able to meet the time limit. This forces us to look for optimized algorithms. + +## Why Go? + +Go is used when stronger typing is required. This helps not to violate the conditions of the task.