problemscpp
A collection of my answers to algorithm problems in c++.
静态 Public 成员函数 | 所有成员列表
leetcode::find_the_closest_palindrome::Solution类 参考

#include <leetcode.h>

静态 Public 成员函数

static string nearestPalindromic (const string &n)
 

详细描述

在文件 leetcode.h1433 行定义.

成员函数说明

◆ nearestPalindromic()

string leetcode::find_the_closest_palindrome::Solution::nearestPalindromic ( const string &  n)
static

在文件 leetcode.cpp3748 行定义.

3748 {
3749 const long long num = stoll(n);
3750 if(num == 10 || num == 11) {
3751 return "9";
3752 }
3753 if(num < 10) {
3754 return to_string(num - 1);
3755 }
3756 int len = n.length();
3757 const bool even = n.length() % 2 == 0;
3758 string prefix = n.substr(0, n.length() / 2 + (even ? 0 : 1));
3759 string option_str[3];
3760 auto rev = string(prefix.rbegin() + (even ? 0 : 1), prefix.rend());
3761 option_str[2] = prefix + rev;
3762 const long long prefix_int[2] = {stoll(prefix) - 1, stoll(prefix) + 1};
3763 string prefix_str[2] = {to_string(prefix_int[0]), to_string(prefix_int[1])};
3764 for(int i = 0; i < 2; i++) {
3765 if(prefix_str[i].length() == prefix.length()) {
3766 rev = string(prefix_str[i].rbegin() + (even ? 0 : 1), prefix_str[i].rend());
3767 option_str[i] = prefix_str[i] + rev;
3768 } else if(prefix_str[i].length() > prefix.length()) {
3769 rev = string(prefix_str[i].rbegin() + (even ? 1 : 2), prefix_str[i].rend());
3770 option_str[i] = prefix_str[i] + rev;
3771 } else if(prefix_str[i].length() < prefix.length()) {
3772 rev = string(prefix_str[i].rbegin(), prefix_str[i].rend());
3773 option_str[i] = prefix_str[i] + (even ? "9" : "") + rev;
3774 }
3775 }
3776 long long option_int[3] = {stoll(option_str[0]), stoll(option_str[1]), stoll(option_str[2])};
3777 sort(option_int, option_int + 3);
3778 long long minimum = option_int[0];
3779 for(int i = 1; i < 3; i++) {
3780 if(abs(option_int[i] - num) < abs(minimum - num) && option_int[i] != num) {
3781 minimum = option_int[i];
3782 }
3783 }
3784 return to_string(minimum);
3785 }

被这些函数引用 leetcode::find_the_closest_palindrome::TEST().


该类的文档由以下文件生成: