Skip to content

Commit

Permalink
feat(564): Hard
Browse files Browse the repository at this point in the history
Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.

The closest is defined as the absolute difference minimized between two integers.

Example 1:

Input: n = "123"
Output: "121"
Example 2:

Input: n = "1"
Output: "0"
Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.

Constraints:

1 <= n.length <= 18
n consists of only digits.
n does not have leading zeros.
n is representing an integer in the range [1, 1018 - 1].
  • Loading branch information
DziedzicGrzegorz committed Aug 24, 2024
1 parent ee396f5 commit df7b68b
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
39 changes: 39 additions & 0 deletions internal/Leetcode/564/564.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package _564

import (
"math"
"strconv"
)

func nearestPalindromic(n string) string {
l := len(n)
res := []int{int(math.Pow10(l-1)) - 1, int(math.Pow10(l)) + 1}
left, _ := strconv.Atoi(n[:(l+1)/2])
for _, x := range []int{left - 1, left, left + 1} {
y := x
if l&1 == 1 {
y /= 10
}
for ; y > 0; y /= 10 {
x = x*10 + y%10
}
res = append(res, x)
}
ans := -1
x, _ := strconv.Atoi(n)
for _, t := range res {
if t != x {
if ans == -1 || abs(t-x) < abs(ans-x) || abs(t-x) == abs(ans-x) && t < ans {
ans = t
}
}
}
return strconv.Itoa(ans)
}

func abs(x int) int {
if x < 0 {
return -x
}
return x
}
34 changes: 34 additions & 0 deletions internal/Leetcode/564/564_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package _564

import (
"testing"
)

func Test_nearestPalindromic(t *testing.T) {
type args struct {
n string
}
tests := []struct {
name string
args args
want string
}{
{
name: "Example 1",
args: args{n: "123"},
want: "121",
},
{
name: "Example 2",
args: args{n: "1"},
want: "0",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := nearestPalindromic(tt.args.n); got != tt.want {
t.Errorf("nearestPalindromic() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit df7b68b

Please sign in to comment.