///根据旧编码获取新编码,编码范围是100~ZZZ,字母部分不包含小写字母,新编码是在旧编码上加1获得的,如果旧编码末位是9,则新编码末位加1变成A,旧编码末位是Z,则新编码第二位加1,末位为0。如果旧编码为ZZZ,则新编码重新从头开始,即100。例如:传入的旧编码为1A5,则新编码为1A6,传入的旧编码为1A9,则新编码为1AA,传入的旧编码为1AZ,则新编码为1B0,传入的旧编码为ZZZ,则新编码为100。...
public string GetNewCode(string strOldCode)
{
///请写出代码
}///因为此函数要频繁使用,所以想求一个最优算法
public string GetNewCode(string strOldCode)
{
///请写出代码
}///因为此函数要频繁使用,所以想求一个最优算法
就按36进制计算
1A9 就是 1*36*36+10*36+9
加1后就是 1*36*36+10*36+9+1
然后再把这个数分别用36除
类似于IP地址转换为数字,具体的方法就不写了,应该可以实现
当然还要处理一下边界,比如ZZZ。
另外一个问题就是字母转数字和数字转字母,这个用字符的ASCII码值和A-10的码值比较就可以了。
事先初始化一个一一对应的StringDictionary
直接查字典得到
{
const string cNumbers = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (strOldCode == null || strOldCode == string.Empty) return strOldCode;
char[] vChars = strOldCode.ToCharArray();
for (int i = vChars.Length - 1; i >= 0; i--)
{
int p = cNumbers.IndexOf(vChars[i]);
if (p < 0) return null; // error
if (p + 1 <= cNumbers.Length - 1)
{
vChars[i] = cNumbers[p + 1];
for (int j = vChars.Length - 1; j > i; j--)
vChars[j] = cNumbers[0];
break;
}
}
return new string(vChars);
}private void button1_Click(object sender, EventArgs e)
{
string s = "000";
for(int i = 0; i < 1000; i++)
{
s = GetNewCode(s);
Console.WriteLine(s);
}
}
{
if (c=='Z')
{
c = '0';
return true;
}
else if(c=='9')
{
c = 'A';
return false;
}
else
{
c++;
return false;
}
}
public string GetNewCode(string strOldCode)
{
if (strOldCode=="ZZZ") return "100";
char[] arr = strOldCode.ToCharArray();
if (GetChar(ref arr[2]))
{
if (GetChar(ref arr[1]))
{
GetChar(ref arr[0]);
}
}
return new string(arr);
}
using System.Diagnostics;namespace ConsoleApplication1
{
class Program
{
static Stopwatch watch = new Stopwatch(); private static bool GetChar(ref char c)
{
if (c == 'Z')
{
c = '0';
return true;
}
else if (c == '9')
{
c = 'A';
return false;
}
else
{
c++;
return false;
}
}
public static string GetNewCode(string strOldCode)
{
if (strOldCode == "ZZZ") return "100";
char[] arr = strOldCode.ToCharArray();
if (GetChar(ref arr[2]))
{
if (GetChar(ref arr[1]))
{
GetChar(ref arr[0]);
}
}
return new string(arr);
}
static void Main(string[] args)
{
string[] arr = new string[10000];
watch.Start();
arr[0] = "100";
for (int i = 0; i < 10000; i++)
{
arr[i+1] = GetNewCode(arr[i]);
}
watch.Stop();
Console.WriteLine("运行10000次,耗时:{0}", watch.Elapsed); Console.ReadLine();
}
}
}
不错。。
--------------------算法大类一种,Google一下就明白了。
for (int i = 0; i < 9999; i++)
{
arr[i+1] = GetNewCode(arr[i]);
}
否则应该会出现越界错误