564. Find the Closest Palindrome
来源:互联网 发布:javascript长度函数 编辑:程序博客网 时间:2024/06/10 09:42
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”
题目大意:
找到最接近n 的回文数
思路:
假如原来的数是a1a2a3a4a5….an,最接近的n的回文数出现在将a1…an对折即a1…a(n/2)的并在之后复制一遍的回文数,当然最后一位随着是否比原数大或小会有一个抖动,因此要搜索-1,0,+1三种情况
此外比如出现99或者100的情况,我们还需要找pow(10, l) + 1(10…..01)和 pow(10, l - 1) - 1(9……9),我们只需要在这5个数中找就可以了
class Solution {public: string nearestPalindromic(string n) { int l = n.size(); set<long> candidates; // biggest, one more digit, 10...01 candidates.insert(long(pow(10, l)) + 1); // smallest, one less digit, 9...9 or 0 candidates.insert(long(pow(10, l - 1)) - 1); // the closest must be in middle digit +1, 0, -1, then flip left to right long prefix = stol(n.substr(0, (l + 1) / 2)); for(int i=-1;i<=1;i++){ string p = to_string(prefix+i); string pp = p + string(p.rbegin()+(1&l),p.rend()); cout <<"pp is "<<pp<<endl; candidates.insert(stol(pp)); } candidates.erase(stol(n)); long minGap = LONG_MAX; string minVar =""; for(auto num : candidates){ long gap = abs(num-stol(n)); if(gap < minGap) { minGap = gap; minVar = to_string(num); } } return minVar; }};
阅读全文
0 0
- 564. Find the Closest Palindrome
- 564. Find the Closest Palindrome
- 564. Find the Closest Palindrome (Hard)
- leetcode 564. Find the Closest Palindrome
- leetcode 564. Find the Closest Palindrome(java)
- [Leetcode] 564. Find the Closest Palindrome 解题报告
- [LeetCode] 564. Find the Closest Palindrome 深入浅出讲解和代码示例
- leetcode 564. Find the Closest Palindrome 距离自己最近的回文数字
- LeetCode 564: Find the Closest Palindrome(python)
- Find the Closest Palindrome:寻找与给定目标大小最接近且尽可能小的回文
- NOJ [1251] Find the Palindrome
- hdu3068 Manacher --> find the longest palindrome
- Find K Closest Elements
- 寻找最近点对问题(FCPP find the closest pair of point)
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- The Closest M Points
- C语言课程设计-教师工作管理系统
- 使用Builder模式封装Dialog和PopupWindow
- centos7 编译安装tensorflow1.2
- jpa nulls last 不起作用
- Java注解(Annotation)详解(四)——注解反射生成SQL语句
- 564. Find the Closest Palindrome
- 省市县三级自身一对一关联的表,联动查询SQL
- HDU
- 移动开发----biu,biu,一个有趣的EditText
- Android源码-高质量开发库
- 【c语言】打开一个客户端socket描述符
- 包装类和正则表达式
- 图像增强(直方图均衡化、拉普拉斯、Log、Gamma)
- 控制开关的printf