字母字符串的整数(a,A,b,B,...,z,Z,aa,AA,ba,Ba,... za,zA,aa,AA,...)

时间:2018-12-23 11:31:23

标签: c#

我找到了获得不同输出的代码,但这可能是解决方案的提示。

public string GetCode(int number)
{
    int start = (int)'A' - 1;
    if (number <= 26) return ((char)(number + start)).ToString();

    StringBuilder str = new StringBuilder();
    int nxt = number;

    List<char> chars = new List<char>();

    while (nxt != 0) {
        int rem = nxt % 26;
        if (rem == 0) rem = 26;

        chars.Add((char)(rem + start));
        nxt = nxt / 26;

        if (rem == 26) nxt = nxt - 1;
    }


    for (int i = chars.Count - 1; i >= 0; i--) {
        str.Append((char)(chars[i]));
    }

    return str.ToString();
}

此方法的输出是

A
B
C
(...)
Z
AA
AB
AC
(...)
AZ 
AAA
(...)

我希望获得略有不同的输出,如标题中所述。最有效的解决方案是什么?

1 个答案:

答案 0 :(得分:0)

与其获取每个数字的代码,不如直接计数。所以我的代码计数到52(a-zA-Z),然后波动并将其加到下一个52位(就像十进制计数一样,到10时再加一个到下一位)。参见下面的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            new RipleCount52(10000);
        }
    }
    public class RipleCount52
    {
        //places are a number from 0 t0 51 indicating each of the 52 charaters
        //the least significant place is index 0
        //when printing character the order has to be reversed so most significant place gets printed first.
        public List<int> places = new List<int>();
        public RipleCount52(int maxNumber)
        {
            int count = 0;
            places.Add(count);
            for (int i = 0; i < maxNumber; i++)
            {
                string output = string.Join("",places.Reverse<int>().Select(x => (x < 26) ? (char)((int)'a' + x) : (char)((int)'A' + x - 26)));
                Console.WriteLine(output);
                places[0] += 1;
                //riple after all 52 letter are printed
                if (count++ == 51)
                {
                    Ripple();
                    count = 0;
                }
            }
        }
        private void Ripple()
        {
            //loop until no ripple is required
            for (int i = 0; i < places.Count(); i++)
            {
                if (places[i] == 52)
                {
                    //all places rippled a new place needs to be added
                    if (i == places.Count - 1)
                    {
                        places[i] = 0;
                        places.Insert(0, 0);
                        break;
                    }
                }
                else
                {
                    //no more ripples are required so exit
                    places[i] += 1;
                    break;
                }
                places[i] = 0;
            }
        }
    }
}