第n个奇数回文数
nth odd digit palindrome number
下面是第n个偶数回文的代码,我想知道第n个奇数回文的代码
#include <bits/stdc++.h>
using namespace std;
// Function to find nth even length Palindrome
string evenlength(string n)
{
// string r to store resultant
// palindrome. Initialize same as s
string res = n;
// In this loop string r stores
// reverse of string s after the
// string s in consecutive manner .
for (int j = n.length() - 1; j >= 0; --j)
res += n[j];
return res;
}
// Driver code
int main()
{
string n = "10";
// Function call
cout << evenlength(n);
return 0;
}
如果你想要一个奇数长度的回文(即 101
输入 10
或 1234321
输入 1234
),你可以将 for 循环替换为:
for (int j = static_cast<int>(n.size()) - 2; j >= 0; --j)
res += n[j];
(注意 n.length() - 2
而不是 n.length() - 1
)
这将在添加反向版本时跳过最后一个字符,这样最后一个数字只出现一次。
因为你想把输入作为一个字符串和return一个字符串,你也可以创建一个新的变量作为输入的子字符串(忽略最后一位),反转它并连接和return.
string Oddlength(string a)
{
string b;
b=a.substr(0,a.size()-1);
reverse(b.begin(),b.end());
a+=b;
return a;
}
这是有效的,因为第 n(n>10) 个奇数位回文数只是与忽略最后一位数字的数字相反的数字连接。而对于 (n<10),它是数字本身。
所以第120个奇数回文数是"120"+"21"="12021"。
第1200个奇数回文数是"1200" + "021"="1200021"。
下面是第n个偶数回文的代码,我想知道第n个奇数回文的代码
#include <bits/stdc++.h>
using namespace std;
// Function to find nth even length Palindrome
string evenlength(string n)
{
// string r to store resultant
// palindrome. Initialize same as s
string res = n;
// In this loop string r stores
// reverse of string s after the
// string s in consecutive manner .
for (int j = n.length() - 1; j >= 0; --j)
res += n[j];
return res;
}
// Driver code
int main()
{
string n = "10";
// Function call
cout << evenlength(n);
return 0;
}
如果你想要一个奇数长度的回文(即 101
输入 10
或 1234321
输入 1234
),你可以将 for 循环替换为:
for (int j = static_cast<int>(n.size()) - 2; j >= 0; --j)
res += n[j];
(注意 n.length() - 2
而不是 n.length() - 1
)
这将在添加反向版本时跳过最后一个字符,这样最后一个数字只出现一次。
因为你想把输入作为一个字符串和return一个字符串,你也可以创建一个新的变量作为输入的子字符串(忽略最后一位),反转它并连接和return.
string Oddlength(string a)
{
string b;
b=a.substr(0,a.size()-1);
reverse(b.begin(),b.end());
a+=b;
return a;
}
这是有效的,因为第 n(n>10) 个奇数位回文数只是与忽略最后一位数字的数字相反的数字连接。而对于 (n<10),它是数字本身。
所以第120个奇数回文数是"120"+"21"="12021"。
第1200个奇数回文数是"1200" + "021"="1200021"。