Skip to content

Maximum Positive Integer Rotations in Golang

The challenge

Write function MaxRot(n) which given a positive integer n returns the maximum number you got doing rotations similar to the above example.

So MaxRot is such as:

  • MaxRot(56789) should return 68957
  • MaxRot(38458215) should return 85821534

Examples:

Take a number: 56789. Rotate left, you get 67895.

Keep the first digit in place and rotate left the other digits: 68957.

Keep the first two digits in place and rotate the other ones: 68579.

Keep the first three digits and rotate left the rest: 68597. Now it is over since keeping the first four it remains only one digit which rotated is itself.

You have the following sequence of numbers:

56789 -> 67895 -> 68957 -> 68579 -> 68597

..and you must return the greatest: 68957.

The solution in Golang

Option 1:

package solution import "strconv" func MaxRot(n int64) int64 { str := strconv.FormatInt(n, 10) max := n for i := ; i<len(str)-1 ; i++ { str = str[:i]+str[i+1:]+string(str[i]) num, _:= strconv.ParseInt(str, 10, 64) if max < num { max = num } } return max }
Code language: Go (go)

Option 2:

package solution import . "strconv" func MaxRot(n int64) int64 { s, max := FormatInt(n,10), n for i := ; i < len(s); i++ { s = s[:i] + s[i:][1:] + s[i:][:1] v,_ := ParseInt(s,10,64) if max < v { max = v } } return max }
Code language: Go (go)

Option 3:

package solution import "strconv" func MaxRot(rot int64) int64 { rotRunes := []rune(strconv.FormatInt(rot, 10)) for index := ; index < len(rotRunes) - 1; index++ { rightPart := append(rotRunes[index + 1:], rotRunes[index]) rotRunes = append(rotRunes[:index], rightPart...) rotVariation, err := strconv.ParseInt(string(rotRunes), 10, 64) if err == nil && rotVariation > rot { rot = rotVariation } } return rot }
Code language: Go (go)

Test cases to validate our solution

package solution_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func dotest(n int64, exp int64) { var ans = MaxRot(n) Expect(ans).To(Equal(exp)) } var _ = Describe("Tests MaxRot", func() { It("should handle basic cases", func() { dotest(38458215, 85821534) dotest(195881031, 988103115) dotest(896219342, 962193428) }) })
Code language: Go (go)

See also  How to Replace Noun Phrases with Pronouns in Golang
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x