Add problem 0007

This commit is contained in:
Ivan R. 2023-11-30 11:56:47 +05:00
parent 2ad850464e
commit 17bdab0a43
Signed by: lumin
GPG key ID: 927D3132247BDE4E
4 changed files with 65 additions and 0 deletions

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module github.com/ordinary-dev/my-solutions
go 1.19

View file

@ -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)
}

View file

@ -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)
}
}

View file

@ -16,6 +16,13 @@ cd random-problem
ruby test.rb ruby test.rb
``` ```
Go:
```bash
cd random-problem
go test ./...
```
## Why Ruby? ## Why Ruby?
Solving problems in Ruby can be a lot more fun than it first appears. 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, Sub-optimal C or Rust solutions will pass all tests,
but Ruby or Python solutions will not be able to meet the time limit. but Ruby or Python solutions will not be able to meet the time limit.
This forces us to look for optimized algorithms. 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.