Add problem 0007
This commit is contained in:
parent
2ad850464e
commit
17bdab0a43
4 changed files with 65 additions and 0 deletions
3
go.mod
Normal file
3
go.mod
Normal file
|
@ -0,0 +1,3 @@
|
|||
module github.com/ordinary-dev/my-solutions
|
||||
|
||||
go 1.19
|
30
leetcode/0007-reverse-integer/main.go
Normal file
30
leetcode/0007-reverse-integer/main.go
Normal 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)
|
||||
}
|
21
leetcode/0007-reverse-integer/main_test.go
Normal file
21
leetcode/0007-reverse-integer/main_test.go
Normal 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)
|
||||
}
|
||||
}
|
11
readme.md
11
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.
|
||||
|
|
Loading…
Reference in a new issue