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"

Note:

  1. The input n is a positive integer represented by string, whose length will not exceed 18.
  2. If there is a tie, return the smaller one as answer.

Approach #1: Logic. [Java]

class Solution {
public String nearestPalindromic(String n) {
Long num = Long.parseLong(n);
Long big = findHigherPalindrome(num+1);
Long small = findLowerPalindrome(num-1);
return Math.abs(num - small) > Math.abs(big - num) ? String.valueOf(big) : String.valueOf(small);
} Long findHigherPalindrome(Long limit) {
String n = Long.toString(limit);
char[] s = n.toCharArray();
int m = s.length;
char[] t = Arrays.copyOf(s, m);
for (int i = 0; i < m / 2; ++i) {
t[m-i-1] = t[i];
}
for (int i = 0; i < m; ++i) {
if (s[i] < t[i]) return Long.parseLong(String.valueOf(t));
else if (s[i] > t[i]) {
for (int j = (m-1) / 2; j >= 0; --j) {
if (++t[j] > '9') t[j] = '0';
else break;
}
for (int k = 0; k < m / 2; ++k) {
t[m-1-k] = t[k];
}
return Long.parseLong(String.valueOf(t));
}
}
return Long.parseLong(String.valueOf(t));
} Long findLowerPalindrome(Long limit) {
String n = Long.toString(limit);
char[] s = n.toCharArray();
int m = s.length;
char[] t = Arrays.copyOf(s, m);
for (int i = 0; i < m / 2; ++i) {
t[m-1-i] = t[i];
}
for (int i = 0; i < m; ++i) {
if (s[i] > t[i]) return Long.parseLong(String.valueOf(t));
else if (s[i] < t[i]) {
for (int j = (m - 1) / 2; j >= 0; --j) {
if (--t[j] < '0') t[j] = '9';
else break;
}
if (t[0] == '0') {
char[] a = new char[m-1];
Arrays.fill(a, '9');
return Long.parseLong(String.valueOf(a));
}
for (int k = 0; k < m / 2; ++k) {
t[m-1-k] = t[k];
}
return Long.parseLong(String.valueOf(t));
}
}
return Long.parseLong(String.valueOf(t));
}
}

  

Analysis:

We first need to find the higher palindrome and lower palidrome respectively. and return the one who has the least different with the input number.

For the higher palindrome, the lower limit is number + 1 while for the lower palindrome, the hight limit is number - 1.

One global solution to find a palindrome is to copy first half part of the array to the last half part, we regards this as standard palindrome.

We need to detect this standard palindrome belongs to higher one or the lower one. And other solutions will be based on this standard one.

For the higher palindrome, if the standard one belongs to higher, we just simply return it. Or we need to change it.

For example, stirng n is 1343, and the standard palindrome is 1331. to get the higher one form the standard palidrome, we start from the first 3, which is (n.length - 1) / 2. Add the number by 1, 9--> 1431) if the added result is not higher than 9, the changing process is finished, otherwise, continuously changing the number of previous index by i. After the changing process, we re-palidrome the string. (1431 --> 1441)

For the lower palidrom, similar idea. But we need to notice that when we decrease a number a number, and if the first character of the string is '0', we need to resize the array of n.length - 1, and fill in with '9'. (for example, n is '1000', the standard palidrome is '1001' (higher one), the lower one '0000' --> '999'.)

Reference:

https://leetcode.com/problems/find-the-closest-palindrome/discuss/102390/Java-solution-with-full-explaination

564. Find the Closest Palindrome的更多相关文章

  1. leetcode 564. Find the Closest Palindrome

    leetcode564题目地址 Given an integer n, find the closest integer (not including itself), which is a pali ...

  2. 【leetcode】564. Find the Closest Palindrome

    题目如下: 解题思路:既然是要求回文字符串,那么最终的输出结果就是对称的.要变成对称字符串,只要把处于对称位置上对应的两个字符中较大的那个变成较小的那个即可,假设n=1234,1和4对称所以把4变成1 ...

  3. [LeetCode] Find the Closest Palindrome 寻找最近的回文串

    Given an integer n, find the closest integer (not including itself), which is a palindrome. The 'clo ...

  4. [Swift]LeetCode564. 寻找最近的回文数 | Find the Closest Palindrome

    Given an integer n, find the closest integer (not including itself), which is a palindrome. The 'clo ...

  5. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

  6. All LeetCode Questions List 题目汇总

    All LeetCode Questions List(Part of Answers, still updating) 题目汇总及部分答案(持续更新中) Leetcode problems clas ...

  7. Leetcode problems classified by company 题目按公司分类(Last updated: October 2, 2017)

    All LeetCode Questions List 题目汇总 Sorted by frequency of problems that appear in real interviews. Las ...

  8. leetcode 学习心得 (3)

    源代码地址:https://github.com/hopebo/hopelee 语言:C++ 517. Super Washing Machines You have n super washing ...

  9. leetcode hard

    # Title Solution Acceptance Difficulty Frequency     4 Median of Two Sorted Arrays       27.2% Hard ...

随机推荐

  1. 2G内存编译android4.0

    http://blog.csdn.net/leerobin83/article/details/7873229 1.Error occurred during initialization of VM ...

  2. android OkHttpUtils 使用JSON数据作为请求参数

    如果就直接将JSON作为请求字符串,服务端会出现中文乱码.所以只需要将请求的整个JSON参数字符串编码一次,然后服务端解码一次.我这里服务端使用的servlet,下面会两段代码贴出. android: ...

  3. excel2007自定义菜单项学习

    参考: http://club.excelhome.net/thread-1288002-1-1.html http://club.excelhome.net/thread-709306-1-1.ht ...

  4. Andrew机器学习第一课

    批梯度下降算法:      训练样本为一个时:更新Θi 让代价函数最小,利用沿梯度下降方向函数会变得越来越小.这个函数是代价函数J关于(Θi )的.这里并没有在讨论x,y. 关于为什么式子(图是复制的 ...

  5. 在eclipse上搭建Roku开发环境

    环境:Oracle VM virtualBox+Ubuntu server 12.0.4.2 LTS+xfce+ Eclipse IDE for C/C++ Developers 4.3.2 参考:h ...

  6. PHP移植小记

    所需文件: Phpnow 1.5.6 文件夹(D盘): SQL Server2005 x86 安装包(D盘‘安装文件文件夹’): 数据库创建命令:   更改sql server 2005的服务器名称 ...

  7. java web 实现文件夹上传(保留目录结构)

    今天我弄了一下文件夹上传(很简单的 首先,我们的html需要这样写 <form action="/file/upload" enctype="multipart/f ...

  8. Zookeeper C++编程实战之主备切换

    默认zookeeper日志输出到stderr,可以调用zoo_set_log_stream(FILE*)设置输出到文件中还可以调用zoo_set_debug_level(ZooLogLevel)控制日 ...

  9. multiprocessing、threading、gevent区别

    1. 进程是资源分配的单位 2. 线程是操作系统调度的单位 3. 进程切换需要的资源很最大,效率很低 4. 线程切换需要的资源一般,效率一般(当然了在不考虑GIL的情况下) 5. 协程切换任务资源很小 ...

  10. Alpha阶段敏捷冲刺(八)

    1.站立式会议 提供当天站立式会议照片一张 2.每个人的工作 (有work item 的ID),并将其记录在码云项目管理中: 昨天已完成的工作. 祁泽文:写了关于统计的按钮的代码. 徐璐琳:完善了&q ...