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. idea配置springBoot项目热加载

    1.在application.properties中禁用模板引擎缓存 比如freemarker:spring.freemarker.cache=false 2.在pom.xml中添加依赖 <de ...

  2. 【Web】网页清除浮动的方法

    网页中,经常用浮动的div来布局,但是会出现父元素因为子元素浮动引起内部高度为0的问题,为了解决这个问题,我们需要清除浮动,下面介绍4中清除浮动的方法. 在CSS中,clear属性用户清除浮动,语法: ...

  3. 乘积最大(NOIP2000&NOIP水题测试(2017082301))

    题目链接:乘积最大 这道题显然是道区间dp. 难度不是很大. 思路也很清晰. 我们设计一个三维状态. ans[l][r][k] 这里表示在闭区间[l,r]上操作k次的最大值. 操作就是加乘号. 转移也 ...

  4. java学习第六周

    这是暑假学习的第六周,在这周我练习了老师给的例题,还是有一些地方看不懂,这周我对那些不懂的地方用看视频来进行解答,以及进行第二次复习. 下周我会对Java进行更加详细的复习,做好笔记,在LeetCod ...

  5. rails 新建user的phonenumber字段

    1.新建字段 //rails g migration add_字段名_to_表名 字段名:字段类型 rails g migration add_title_to_contents title:stri ...

  6. 数学小知识点整理(TBC)

    文章目录 前言 素数与同余 线性筛部分 素数 线性递推逆元 指数循环节降幂 当求逆元时模数与求逆元的数有可能不互质时的处理方法 一个神奇的结论 拓展欧拉定理 杂乱的一些性质/技巧 二进制枚举子集 异或 ...

  7. ant Design和ant Design mobile的使用,并实现按需加载

    1.全局安装yarn npm install -g create-react-app yarn 2.创建react项目,并用yarn start 运行 3.引入antd/引入antd-mobile y ...

  8. hashable/iterable与orderable

    ################ # hashable协议 # ################ # 一个对象能被称为hashable,它必须实现__hash__与_eq__方法: >>& ...

  9. Codeforces Round #538 (Div. 2) E 随机数生成

    https://codeforces.com/contest/1114/problem/E 题意 交互题,需要去猜一个乱序的等差数列的首项和公差,你能问两种问题 1. 数列中有没有数比x大 2. 数列 ...

  10. mysql学习之路_事物_存储过程_备份

    数据备份与还原 备份:将当前已有的数据保留. 还原:将已经保留的数据恢复到对应表中 为什么要做数据备份 1,防止数据丢失,被盗,误操作 2,保护数据记录 数据备份还原方式有多种:数据表备份 单表数据备 ...