问题陈述:对于给定的正数,我必须立即找出下一个回文。例如:
For 808, output:818
2133, output:2222
我想知道我的代码是否有效,效率如何?这是解决问题的好方法吗?
逻辑解释:我已经设置i
到数字的最左边,j
最右边的位置我基本上是在比较两个数字。我总是分配num[j]=num[i]
,并跟踪数字是否大于原始值、小于或等于。最后,即:j-i==1 or j==i
,根据数字的位数是偶数还是奇数,我看看数字是否变得更大,并做出相应的决定。
编辑:这个数字可以长达 100,000 位!..这是问题陈述的一部分,所以我试图避免暴力方法。
int LeftNineIndex = 0, RightNineIndex = 0;
bool NumberLesser = false, NumberGreater = false;
string number = Console.ReadLine();
char[] num = number.ToCharArray();
int i, j, x, y;
for (i = 0, j = num.Length - 1; i <= j; i++, j--)
{
char m;
Int32.TryParse(num[i].ToString(),out x);
Int32.TryParse(num[j].ToString(), out y);
if (x > y)
{
NumberGreater = true;
NumberLesser = false;
}
else if (x < y)
{
if (j - i == 1)
{
NumberGreater = true;
NumberLesser = false;
x = x + 1;
Char.TryParse(x.ToString(), out m);
num[i] = m;
}
else
{
NumberGreater = false;
NumberLesser = true;
}
}
if ((j == i && NumberGreater == false) || (j - i == 1 && x == y && NumberGreater == false))
{
if (x != 9) // if the number is 9, then i can't add 1 to it
{
x = x + 1;
Char.TryParse(x.ToString(), out m);
num[i] = m;
}
else
{
if (num.Length != 1)
{
Int32.TryParse(num[LeftNineIndex].ToString(), out x);
Int32.TryParse(num[RightNineIndex].ToString(), out y);
x = x + 1;
Char.TryParse(x.ToString(), out m);
num[LeftNineIndex] = m;
num[RightNineIndex] = m;
}
else
{
// user has entered just '9', in which case I've hard-coded
Console.WriteLine("11");
}
}
}
num[j] = num[i];
if (x != 9) //gives us the index of the number closest to the middle, which is not 9
{
LeftNineIndex = i;
RightNineIndex = j;
}
}
Console.WriteLine(num);