1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- func nearestPalindromic(n string) string {
- set := make([]int, 0, 5)
- l := len(n)
- set = append(set, int(math.Pow10(l))+1)
- set = append(set, int(math.Pow10(l-1))-1)
- r1, r2, r3 := []rune(n), []rune(n), []rune(n)
- beg, end := l/2-1+l&1, l/2
- if r1[beg] != '0' {
- r1[beg]--
- }
- if r3[beg] != '9' {
- r3[beg]++
- }
- for ; end < l; beg, end = beg-1, end+1 {
- r1[end] = r1[beg]
- r2[end] = r2[beg]
- r3[end] = r3[beg]
- }
- n1, _ := strconv.Atoi(string(r1))
- n2, _ := strconv.Atoi(string(r2))
- n3, _ := strconv.Atoi(string(r3))
- set = append(set, n1)
- set = append(set, n2)
- set = append(set, n3)
- num, _ := strconv.Atoi(n)
- min, res := math.MaxInt32, math.MaxInt32
- for _, i := range set {
- if det := abs(num - i); det != 0 && det < min || (det == min && i < res) {
- min, res = det, i
- }
- }
- return strconv.Itoa(res)
- }
- func minInt(x, y int) int {
- if x < y {
- return x
- }
- return y
- }
- func abs(x int) int {
- if x < 0 {
- return -x
- }
- return x
- }
|