Palindrome
LC 564. Find the Closest Palindrome
Given an integer n, find the closest integer (not including itself), which is a palindrome.
The ‘closest’ is defined as absolute difference minimized between two integers.
Example 1:
Input: “123”
Output: “121”
- Idea: two kinds of solution
- the result has the same length as the input string
- get first half of the string, if the length of string is odd, then the first half should include the middle letter. -> reverse the first half of the string(this time we should exclude the middle letter if the string has one). -> link them
- example : string 23456 -> first half : 234 -> reverse : 32 -> link 23432
- the result has the different length with the input string
- there are only 4 cases
- example: input 999 -> len = 3 -> 10^3 - 1 = 999, 10^3 + 1 = 1001, 10^2-1 = 99, 10^2 + 1 = 101
- the result has the same length as the input string
- Corner cases
- length = 1: return the number - 1
- the result set should not include the input
1 |
void (vector<long>& res, string halfn, int len){ |
近期评论