我目前是C ++学生,而且我正处于C ++的基础部分,所以请原谅我这对你们来说似乎很简单,但我觉得这是我遇到过的最难的问题: 给出一个数字n,正好是8位数。找到通过重新排列n的所有数字获得的最大回文数。 示例:21523531 => 53211235
我知道向量以及如何检查数字是否为回文,我也知道如何从数字中删除每个数字,直到它给出一个回文数,但我不知道如何重新排列所有数字。
答案 0 :(得分:0)
这是非常简单的逻辑。首先计算0-9的不同位数。如果不同的数字不超过4,则计算每个数字的实例。如果每个数字都是偶数,那么找到4个最大的数字(所有数字都可以相等)。 首先按降序排序,然后按顺序递增。 这将有效。 谢谢。
答案 1 :(得分:0)
在偶数k数的回文数中,每个数字d都出现
n(d) = 2 * m(d), m(d) in |N u {0}
次。
只需将数字反向排序为数组source
和
(伪代码)
for i=0 to i = (k/2)-1
do
target[i] = target[k-1-i] = source[i*2];
done
现在尝试用C ++编写代码。
答案 2 :(得分:0)
我认为以下代码可行:
public static string GetMASM32LocationFromRegistry()
{
RegistryKey localMachineRegistryKey;
RegistryKey masm32RegistryKey;
RegistryView currentRegistryView = RegistryView.Registry64;
localMachineRegistryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, currentRegistryView);
masm32RegistryKey = localMachineRegistryKey.OpenSubKey(@"SOFTWARE\Wow6432Node\MASM32");
if (masm32RegistryKey == null)
{
return @"ERROR: The registry key HKLM\SOFTWARE\Wow6432Node\MASM32 could not be found";
}
StringBuilder masm32RegistryKeyValuesBuilder = new StringBuilder("Key/Value pairs for registry key HKLM\\SOFTWARE\\Wow6432Node\\MASM32:\r\n");
foreach (string masm32RegistryKeyValueName in masm32RegistryKey.GetValueNames())
{
masm32RegistryKeyValuesBuilder.AppendFormat
(
"Key: [{0}], Value: [{1}], Value Type: [{2}]\r\n",
masm32RegistryKeyValueName,
masm32RegistryKey.GetValue(masm32RegistryKeyValueName),
masm32RegistryKey.GetValueKind(masm32RegistryKeyValueName)
);
}
return masm32RegistryKeyValuesBuilder.ToString();
}
这里有更多学生可读的版本:
int func(int x) // returns 0 if there is no valid palindrome
{
int arr[10]{};
while (x)
{
arr[x%10]++;
x /= 10;
}
for (int it : arr)
if (it % 2)
return 0;
int ret = 0;
for (int i = 9; i >= 0; i--)
for (int j = 0; j < arr[i]/2; j++)
ret = ret * 10 + i;
for (int i = 0; i < 10; i++)
for (int j = 0; j < arr[i]/2; j++)
ret = ret * 10 + i;
return ret;
}
我希望你会发现这个答案很有用,并且会在没有盲目复制的情况下使用它。