TLDR (and simplified): Given a string s
, where s
is any positive integer, reverse the order and summate each digit multiplied by it's new index ( 1).
For example, the value returned from "98765" would be: (1x5) (2x6) (3x7) (4x8) (5*9)= 115
.
My current working solution can be found here: Go playground. I'd like to know whether there's a better way of doing this, be it readability or efficiency. For example, I decided in favour of a count
variable instead utilising i
and len
as it seemed clearer. I'm also not very familiar with int
/string
conversions but I'm assuming making use of strconv
is required.
func reverseStringSum(s string) int {
total := 0
count := 1
for i := len(s) - 1; i >= 0; i-- {
char := string([]rune(s)[i])
num, _ := strconv.Atoi(char)
total = count * num
count
}
return total
}
CodePudding user response:
Maybe this is more efficient
func reverseStringSum(s string) int {
total := 0
count := 1
for i := len(s) - 1; i >= 0; i-- {
num, _ := strconv.Atoi(string(s[i]))
total = count * num
count
}
return total
}
CodePudding user response:
An efficient way to solve the complete problem: sum("987-65") = 115
. The complete problem is documented in your working solution link: https://go.dev/play/p/DJ1ZYYDFnfq.
package main
import "fmt"
func reverseSum(s string) int {
sum := 0
for i, j := len(s)-1, 0; i >= 0; i-- {
d := int(s[i] - '0')
if 0 <= d && d <= 9 {
j
sum = j * d
}
}
return sum
}
func main() {
s := "987-65"
sum := reverseSum(s)
fmt.Println(sum)
}
https://go.dev/play/p/y9oHALv-3ii
115
Since we are talkng about efficient Go code, we need some Go benchmarks.
$ go test reversesum_test.go -bench=. -benchmem
BenchmarkSumTBJ-8 4001182 295.8 ns/op 52 B/op 6 allocs/op
BenchmarkSumA2Q-8 225781720 5.284 ns/op 0 B/op 0 allocs/op
reversesum_test.go
:
package main
import (
"strconv"
"strings"
"testing"
)
func reverseSumTBJ(s string) int {
total := 0
count := 1
for i := len(s) - 1; i >= 0; i-- {
char := string([]rune(s)[i])
num, _ := strconv.Atoi(char)
total = count * num
count
}
return total
}
func reverseSumA2Q(s string) int {
sum := 0
for i, j := len(s)-1, 0; i >= 0; i-- {
d := int(s[i] - '0')
if 0 <= d && d <= 9 {
j
sum = j * d
}
}
return sum
}
func BenchmarkSumTBJ(b *testing.B) {
for n := 0; n < b.N; n {
rawString := "987-65"
stringSlice := strings.Split(rawString, "-")
numberString := stringSlice[0] stringSlice[1]
reverseSumTBJ(numberString)
}
}
func BenchmarkSumA2Q(b *testing.B) {
for n := 0; n < b.N; n {
rawString := "987-65"
reverseSumA2Q(rawString)
}
}