kar*_*n k 5 c# arrays palindrome
问题陈述:对于给定的正数,我必须立即找出下一个回文.例如:
For 808, output:818
2133, output:2222
Run Code Online (Sandbox Code Playgroud)
我想知道我的代码是否有效,以及它的效率如何?这是解决问题的好方法吗?
逻辑解释:我已经设置i到数字的最左边位置,j到最右边的位置,我基本上比较了2个数字.我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);
Run Code Online (Sandbox Code Playgroud)
在恒定时间内找到下一个回文是相对简单的:
该BigInteger类型对于实现此功能非常有用:
这种方法在输入长度上具有线性成本,即它与数字的大小成对数.
public static BigInteger NextPalindrome(BigInteger input)
{
string firstHalf=input.ToString().Substring(0,(input.ToString().Length+1)/2);
string incrementedFirstHalf=(BigInteger.Parse(firstHalf)+1).ToString();
var candidates=new List<string>();
candidates.Add(firstHalf+new String(firstHalf.Reverse().ToArray()));
candidates.Add(firstHalf+new String(firstHalf.Reverse().Skip(1).ToArray()));
candidates.Add(incrementedFirstHalf+new String(incrementedFirstHalf.Reverse().ToArray()));
candidates.Add(incrementedFirstHalf+new String(incrementedFirstHalf.Reverse().Skip(1).ToArray()));
candidates.Add("1"+new String('0',input.ToString().Length-1)+"1");
return candidates.Select(s=>BigInteger.Parse(s))
.Where(i=>i>input)
.OrderBy(i=>i)
.First();
}
Run Code Online (Sandbox Code Playgroud)
通过与本机实现进行比较,测试使用100000以下的所有正整数.
第五种情况很容易被遗漏.如果数字由全部9s 组成,则递增前半部分会改变长度,如果当前长度为奇数(,...)9,则需要额外处理999.
| 归档时间: |
|
| 查看次数: |
1245 次 |
| 最近记录: |