Skip to content

Instantly share code, notes, and snippets.

@ffrizzo
Created November 8, 2022 17:40
Show Gist options
  • Save ffrizzo/e3de6fd41299962819c4f77e757f2fac to your computer and use it in GitHub Desktop.
Save ffrizzo/e3de6fd41299962819c4f77e757f2fac to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strconv"
)
// Write a function that takes an integer as an input and return the next number that is a palindrome.
func main() {
numbers := []int{
9,
10,
11,
120,
121,
12220,
12221,
1200,
12000,
122222,
12222,
1200700022,
1200770022,
1222221,
}
for _, v := range numbers {
fmt.Printf("Next palindrome of %d is %d\n", v, palindrome(v))
}
}
func palindrome(input int) int {
if input < 10 {
return 11
}
strInput := strconv.Itoa(input)
length := len(strInput) / 2
var middle string
if len(strInput)%2 != 0 {
middle = strInput[length : length+1]
}
left := strInput[0:length]
right := Reverse(left)
output := left + middle + right
intOutput, _ := strconv.Atoi(output)
if input < intOutput {
return intOutput
}
if middle == "" {
intLeft, _ := strconv.Atoi(left)
left = strconv.Itoa(intLeft + 1)
} else {
intMiddle, _ := strconv.Atoi(middle)
middle = strconv.Itoa(intMiddle + 1)
}
output = left + middle + Reverse(left)
intOutput, _ = strconv.Atoi(output)
return intOutput
}
func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment